This is Part II in our Using Jest and Testing Library with React Native tutorial series. This series covers getting set up with and using Jest and Testing Library with React Native.
Seriers Outline:
- Part I: Setting Up
- Part II: Writing the First Test – Current Article
- Part III: Testing for an Element That Isn’t Present
- Part IV: Button Testing
- Part V: Testing Styles of a Component
- Part VI: Functional Testing
- Part VII: Further Helpful Information
In our last tutorial (Part I), I gave a brief overview and explanation of Jest, Testing Library, and React Native. Then, we walked through how to get set up. This post will cover the steps you’ll need to take to write your first test. I’ll also break down the code, so you have a clear understanding of the process. Let’s get started!
Hello World!
For our first test, let’s test a Hello World string. Classic.
In the root directory of the project, open App.js
. Then, replace all the code you find there with this code:
import React from 'react'; import {StyleSheet, Text, View} from 'react-native'; const App = () => { return ( <View style={styles.body}> <View style={styles.sectionContainer}> <Text style={styles.sectionTitle}>Hello World!</Text> </View> </View> ); }; const styles = StyleSheet.create({ body: { backgroundColor: '#ffffff', }, sectionContainer: { marginTop: 32, paddingHorizontal: 24, }, sectionTitle: { fontSize: 24, fontWeight: '600', color: '#000000', }, }); export default App;
*After you’ve replaced the code, you can run the app to see what it looks like! For the sake of this post, we’ll skip over this and stay focused on testing the component.*
Adding a Test File
In the root of the project directory, add a new folder and name it __tests__
. Next, we’ll add a new file to our newly created folder. Let’s name it App.test.js
.
Inside of App.test.js
, add this code:
import React from 'react'; import {cleanup, render} from '@testing-library/react-native'; import App from '../App'; afterEach(cleanup); describe('App', () =>; { it('should show hello world', () =>; { const helloWorldText = 'Hello World!'; const {toJSON, getByText} = render(<App />); const foundHelloWorldText = getByText(helloWorldText); expect(foundHelloWorldText.props.children).toEqual(helloWorldText); expect(toJSON()).toMatchSnapshot(); }); });
Now, open up a terminal or command prompt in the root of the project directory.
If you’re using yarn, write or paste yarn test
. If you’re using npm, write or paste npm test
.
Then, simply press return or enter on your keyboard. You should see the following.
And now, congratulations are in order. You have written your first test! You’re so awesome!
A Closer Look at the Test
Let’s take a closer look at what we just did. Rather than leaving you to wonder hopelessly what’s going on, I’ll break down the code line-by-line.
import React from 'react';
Since we are rendering a component (App.js
), and we can’t run JSX without it, we must begin by importing React.
import {cleanup, render} from '@testing-library/react-native';
This line imports the components we use from the testing library.
import App from '../App';
This imports the local component that we want to test.
afterEach(cleanup);
After each test clean up by unmount the React tress that where mounted from render
. This is to help prevent memory leaks.
describe('App', () => {...});
This is used to name the suite of test(s) that we are running. In the image above, you can see:
If we had more tests, they would be intended under App
.
it('should show hello world', () => {..}
This is the name of the test we want to run. There are two names we can use: it
or test
. it
is an alias of test
.
My personal preference is it
. In my opinion, it fits more naturally with the name of the test. should show hello world
is also a personal preference. I usually start any test I write with should. “Should show test,” “should throw error,” “should return something,” etc. You don’t need to follow this method, but I recommend following some sort of pattern in naming. It will make it easier to read when running the test(s).
const helloWorldText = 'Hello World!';
This line stores the text we are testing so we don’t need to repeat it. You can put 'Hello World!'
each place we have helloWorldText
.
const {toJSON, getByText} = render();
This is where the test is ran. We are extracting toJson
and getByText
from the the component after it is ran.
toJson
and getByText
are apart of @testing-library/react-native
API’s. We have access to other API’s and queries as well.
Additionally, with this line, we are using object deconstruction. Keep in mind, we also could have written this as const test = render(...)
and got them from test.toJSON
and test.getByText
.
const foundHelloWorldText = getByText(helloWorldText); getByText
This function takes a string argument (in our case, ‘Hello World!’) and tries to find it in the component. If it’s found, it assigns it to the foundHelloWorldText
variable. If not, it will throw an error. We will go over this error in a later post.
expect(foundHelloWorldText.props.children).toEqual(helloWorldText);
This uses Jest’s Expect to test that the children of foundHelloWorldText
equal ‘Hello World!’
We are going into props.children
because foundHelloWorld
is the code of the component, not the text. If we try to test foundHelloWorldText
against HelloWorld!, you will get an error. To see the code for the component, you can log foundHelloWorldText
in the test by putting console.log(foundHelloWorldText)
below that component.
expect(toJSON()).toMatchSnapshot();
Here, we are using Jest’s snapshot to test the UI of the component we wrote. toJSON()
is a function that renders the code for the UI.
If you look in the __snapshots__
folder under the __test__
folder, you should see a file named App.test.js.snap
. This contains the code of the snapshot test. In later post, we will go over a failed snapshot and how to handle it.
Summary
In summary, in this post (Part 2 of Using Jest and Testing Library with React Native), we successfully created and ran our first test.
First, we updated the code in App.js
. Then, we added a __tests__
directory and a App.test.js
file. Next, I shared the code and process of running your very first test. Finally, we took a closer look at that code, and I broke it down for you, line-by-line.
In the next tutorial (Part 3 of the series), we will go over what to do if an element is undefined/not found. Stay tuned!
[Editor’s Note: Never miss a post by subscribing to receive new blogs by email. No spam, opt-out anytime.]