This post is part of my series on unit testing with Jest in React Native. You can find the introduction here.
In the previous parts, I went through why unit testing is vital and how to test your components using snapshots. While snapshot testing is effective, it fails to test some aspects of the component. Now I would like to talk about more advanced component testing in react native.
One of the first things you probably want to test is the actual content that is being rendered. Let us define a component that will accept some text via props and display it:
This component takes text from
value prop, wraps it with a
View and outputs it with a red color. Now, we want to test these things:
- That it accurately renders the text from the
- That it is wrapped with a
- That the text is red
To render and assert the components, we are going to use the
react-native-testing-library. I do not recommend using
enzyme at the moment as it does not support react native natively (pun intended).
You probably noticed the strange
testID prop on
Text. This prop allows us to query these components later when we write the test. It works similarly to the
id attribute in HTML.
react-native-testing-library comes with a lot of queries available, which you can read about here. Now, time to write the tests:
The first test is the snapshot test, which should already look familiar. Then, we test for the rendered text. You can see that we query the
Text component using
getByTestId, which is quite convenient. We then access the component’s props to check for
afterEach hook on line 5. This cleans up the rendering context after each test to prevent memory leaks.
Now you have an idea of how to assert a component’s output. But what about interaction? For example, you have a component with a text input and a button to submit it:
I tried to keep everything as simple as possible: we have a controlled input that calls the
onChange prop and a button that calls
onSubmit. In order to test it, provide mock functions to these props:
I covered mock functions in the previous part. They are created with
jest.fn() and you can later assert if they were ever called and with what arguments.
Using these approaches, you will be unstoppable while testing your react-native components. In the coming posts, I will talk about redux integration into your unit tests.