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

10
我正在使用React Test Renderer和Jest测试我的React Native应用程序。下面是我所做的简单代码示例:

我使用React Test Renderer与Jest来测试我的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);
});

第一次测试失败,显示:

Expected: 1
Received: 2

第二个测试也失败了:

Expected: 2
Received: 4
为什么使用findAllByProps时,React测试渲染器会找到双倍的实例?
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);
});
2个回答

8

在react-native中存在未解决的问题(链接)

目前唯一的解决方法是:

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

expect(findAllByTestID(instance).length).toEqual(2);

1
感谢您链接这个问题。非常令人沮丧的是,Facebook忽视了这个问题。 - J. Hesters
对于某些组件,它们可能无法正常工作。例如,如果我想要查找TouchableOpacity,则需要稍微修改代码:const findAllByTestID = (instance) => instance.findAll(el => el.props.testID === 'foo' && el.type.displayName === 'TouchableOpacity');expect(findAllByTestID(instance).length).toEqual(2); - Jan Tumanov

1

在测试ReactJS组件时,我遇到了同样的问题。

我深入研究后发现,在某些情况下,findAllByProps可能会返回两个与查询匹配的TestInstance,但它们并不代表相同的实体。第一个实体表示传递给组件的props,第二个实体表示具有整个结构和应用的props的实际组件。

在我的情况下,我一直在查询某个className的组件。通常,构建的组件将拥有多个聚合类的className(我们通过props传递的类以及我们内部应用的类),但是我已经模拟了组件,并且mock只使用通过props传递的class。这样,我就得到了两个具有相同单词className的实体,第一个仅存储props和className是其中之一,第二个则表示处理属性的mock,通过将其直接传递给元素来处理该属性,使其className等于props.className

我通过将TestInstance对象序列化为JSON来找到该机制。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接