如何在我的React Native应用程序中使用Jest/RTL测试特定元素是否具有特定属性?

fae0ux8s  于 2023-11-21  发布在  React
关注(0)|答案(1)|浏览(166)

我的toHaveProperty匹配器给我错误。我相信我使用它不正确。
我在React Native组件中有一个虚拟组件:

// Dummy.tsx
const Dummy: FC<Props> = ({num, onPressHandler}: Props) => {
  const [state, setState] = useState(false);

  return (
    <View testID="dummy" style={styles.container}>
      <Text>abcdef</Text>
      <Text>{num}</Text>
      <Button title={'Press'} onPress={onPressHandler} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'black',
  },
});

字符串
我需要测试testId为“dummy”的View组件是否应用了正确的样式。
我想使用toHaveProperty来检查正确的样式。所以这是我在测试文件中所做的:

// Dummy.test.tsx

describe('dummytest', () => {
  test('prop', () => {
    render(<Dummy num={42} onPressHandler={() => {}} />, {});

    const element = screen.getByTestId('dummy2');
    expect(element).toHaveProperty('style', {
      flex: 1,
      backgroundColor: 'black',
    });
  });
});


然而,我得到了这个错误:

expect(received).toHaveProperty(path, value)

    Expected path: "style"
    Received path: []

    Expected value: {"backgroundColor": "black", "flex": 1}
    Received value: {"_fiber": {"_debugHookTypes": null, "_debugNeedsRemount": false, "_debugOwner": [FiberNode], "_debugSource": null, "actualDuration": 0, "actualStartTime": -1, "alternate": null, "child": [FiberNode], "childLanes": 0, "deletions": null, "dependencies": null, "elementType": "View", "flags": 0, "index": 0, "key": null, "lanes": 0, "memoizedProps": [Object], "memoizedState": null, "mode": 0, "pendingProps": [Object], "ref": null, "return": [FiberNode], "selfBaseDuration": 0, "sibling": null, "stateNode": [Object], "subtreeFlags": 9439749, "tag": 5, "treeBaseDuration": 0, "type": "View", "updateQueue": null}}

       7 |
       8 |     const element = screen.getByTestId('dummy');
    >  9 |     expect(element).toHaveProperty('style', {
         |                     ^
      10 |       flex: 1,
      11 |       backgroundColor: 'black',
      12 |     });

      at Object.toHaveProperty (__tests__/Dummy.test.tsx:9:21)


我是否正确使用了toHaveProperty匹配器?

pbossiut

pbossiut1#

我找到了答案。我应该这样称呼它:

expect(element).toHaveProperty('props.style', {
      flex: 1,
      backgroundColor: 'black',
    });

字符串
主要的区别是它需要是'props.style'而不仅仅是'style'

相关问题