Explain how to use jest to test the react native component in the project, jestreact
At present, there are many Javascript testing tools, but for React testing strategies, Facebook's standard ReactJs testing tool is Jest. Jest official website address: https://facebook.github.io/jest /. We can see that the official Jest website claims the Painless JavaScript Testing. Is a JavaScript unit test framework that Facebook uses to test services and React applications.
The so-called unit test is to test each unit. Generally, it targets functions, classes, or individual components, and does not involve systems or integration. Unit testing is a basic test of software testing. Jest has the following features:
- Adaptability: Jest is modular, scalable, and configurable.
- Sandbox and fast: Jest virtualizes the JavaScript environment, simulates the browser, and runs
- Snapshot test: Jest can quickly write and test snapshots or other serialized values on the React tree to provide a user experience of rapid updates.
- Support for asynchronous code testing: Support for promises and async/await
- Automatically generate static analysis results: not only the test case execution results are displayed, but also the coverage rates of statements, branches, and functions are displayed.
Why unit test tools?
During the development process, we can still write code for unit testing without using the test tool, but our code has a mutual call relationship, during the test, if we want to make the unit relatively independent and run normally, we need to mock the dependent functions and environment of the function to be tested, there are many similarities in test data input, test execution, and test result check. The test tool provides us with convenience in these aspects.
Preparation Phase
An rn project is required. Here we will demonstrate my personal project ReactNative-release xsaga-TODO.
Install jest
If you create an rn project using the react-native init command line and your rn version is later than 0.38, no installation is required. If you are not clear about it, take a look.
Whether the package. json file contains the following code:
// package.json "scripts": { "test": "jest" }, "jest": { "preset": "react-native" }
If not, install npm I jest -- save-dev and add the above Code to the corresponding location of the package. json file.
After completing the preceding steps, run npm run test to test whether the jest configuration is successful. However, if we do not write test cases, pipeline will print no tests found. The configuration is complete.
Snapshot Test
Write a component
import React from 'react';import { Text, View,} from 'react-native';import PropTypes from 'prop-types';const PostArea = ({ title, text, color }) => ( <View style={{ backgroundColor: '#ddd', height: 100 }}> <Text style={{ fontSize: 30 }}>{title}</Text> <Text style={{ fontSize: 15, color }}>{text}</Text> </View>);export default PostArea;
Find the _ test _ folder in the root directory of the project. Now, let's use the React test Renderer and Jest snapshot function to interact with the component, capture the output and create a snapshot file.
// PostArea_test.jsimport 'react-native';import React from 'react';import PostArea from '../js/Twitter/PostArea';import renderer from 'react-test-renderer';test('renders correctly', () => { const tree = renderer.create(<PostArea title="title" text="text" color="red" />).toJSON(); expect(tree).toMatchSnapshot();});
Then run npm run test or jest on the terminal. The output is as follows:
PASS _ tests __\ PostArea_test.js (6.657 s)
√ Renders correctly (5553 ms)
› 1 snapshot written.
Snapshot Summary
› 1 snapshot written in 1 test suite.
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 1 added, 1 total
Time: 8.198 s
Ran all test suites.
At the same time, a file is output in the test folder, that is, the generated snapshot.
// Jest Snapshot v1, https://goo.gl/fbAQLPexports[`renders correctly 1`] = `<View style={ Object { "backgroundColor": "#ddd", "height": 100, } }> <Text accessible={true} allowFontScaling={true} disabled={false} ellipsizeMode="tail" style={ Object { "fontSize": 30, } } > title </Text> <Text accessible={true} allowFontScaling={true} disabled={false} ellipsizeMode="tail" style={ Object { "color": "red", "fontSize": 15, } } > text </Text></View>`;
Modify source file
During the next test, the output will be compared with the previous snapshot. The Snapshot should be submitted together with the code. When the snapshot test fails, you need to check whether the changes are intentionally or unintentionally made. If the change is the same as expected, call jest-u to overwrite the current snapshot.
Let's change the original code: Change the font size of the second <Text> to 14.
<Text style={{ fontSize: 14, color }}>{text}</Text>
Then run jest. In this case, the terminal will throw an error and point out the error location.
Because this code is intentionally modified, jest-u is run and the snapshot is overwritten. If you execute jest again, no error will be reported ~
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.