Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Test Renderer: findAllByProps return double of what It should find when looking for testID in React Native

I'm using React Test Renderer with Jest to test my React Native app.

Here is a simple code example of what I'm doing:

it('renders one text', () => {
  const text = 'bar';
  const instance = renderer.create(
    <View>
      <Text testID="foo">{text}</Text>
    </View>
  ).root;
  expect(instance.findAllByProps({ testID: 'foo' }).length).toEqual(1);
});

it('renders two texts', () => {
  const text = 'bar';
  const instance = renderer.create(
    <View>
      <Text testID="foo">{text}</Text>
      <Text testID="foo">{text}</Text>
    </View>
  ).root;
  expect(instance.findAllByProps({ testID: 'foo' }).length).toEqual(2);
});

The first test fails saying:

Expected: 1
Received: 2

And the second test also fails:

Expected: 2
Received: 4

Why does react test renderer using findAllByProps find double the instances?

PS: As a sanity check I also tried findByProps which works:

it('renders one text', () => {
  const text = 'bar';
  const instance = renderer.create(
    <View>
      <Text testID="foo">{text}</Text>
    </View>
  ).root;
  expect(instance.findByProps({ testID: 'foo' }).props.children).toEqual(text);
});
like image 883
J. Hesters Avatar asked Apr 18 '19 11:04

J. Hesters


People also ask

How do I use testrenderer in react?

Create a TestRenderer instance with the passed React element. It doesn’t use the real DOM, but it still fully renders the component tree into memory so you can make assertions about it. Returns a TestRenderer instance. Similar to the act () helper from react-dom/test-utils, TestRenderer.act prepares a component for assertions.

Why does findallbyprops return two testinstances?

I've taken a deeper look into it and it turns out that under certain conditions findAllByPropsmay return two TestInstances matching the query, however those do not represent the same entity. The first entity represents the props passed to the component, the second the actual component with it's whole structure and props applied.

Is there a work-around for findallbytestid in React Native?

6 There is unresolved issue on react-native Currently the only work-around is: const findAllByTestID = (instance) => instance.findAll(el => el.props.testID === 'foo' && el.type === 'Text'); expect(findAllByTestID(instance).length).toEqual(2);

What is the react renderer package?

This package provides a React renderer that can be used to render React components to pure JavaScript objects, without depending on the DOM or a native mobile environment.


1 Answers

There is unresolved issue on react-native

Currently the only work-around is:

const findAllByTestID = (instance) => instance.findAll(el => el.props.testID === 'foo' && el.type === 'Text');

expect(findAllByTestID(instance).length).toEqual(2);
like image 63
Ilarion Halushka Avatar answered Nov 10 '22 16:11

Ilarion Halushka