React 测试渲染器:findAllByProps 返回在 React Native 中查找 testID 时应该找到的两倍

J. *_*ers 6 reactjs jestjs react-native react-test-renderer

我正在使用带有 Jest 的 React Test Renderer 来测试我的 React Native 应用程序。

这是我正在做的一个简单的代码示例:

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);
});
Run Code Online (Sandbox Code Playgroud)

第一个测试失败说:

Expected: 1
Received: 2
Run Code Online (Sandbox Code Playgroud)

第二个测试也失败了:

Expected: 2
Received: 4
Run Code Online (Sandbox Code Playgroud)

为什么使用findAllByProps查找两倍的实例来响应测试渲染器?

PS:作为健全性检查,我也尝试过findByProps哪些有效:

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);
});
Run Code Online (Sandbox Code Playgroud)

Hil*_*hka 6

反应原生存在未解决的问题

目前唯一的解决方法是:

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

expect(findAllByTestID(instance).length).toEqual(2);
Run Code Online (Sandbox Code Playgroud)