Search code examples
react-nativeunit-testingreact-testing-libraryts-jest

How to test if a particular element has a particular property using Jest/RTL in my React Native application?


My toHaveProperty matcher is giving me error. I believe that I am using it incorrectly.

I have this dummy component in my React Native component:

// 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',
  },
});

I need to test if the View component with testId of "dummy" has been applied the correct styling.

I wanted to use toHaveProperty to check for the correct styling. So this is what I did in my test file:

// 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',
    });
  });
});

However, I am getting this error:

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)

Am I using the toHaveProperty matcher correctly?


Solution

  • I found an answer. I am supposed to call it like this:

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

    The main different is it needs to be 'props.style' rather than just 'style'