// PostArea_test.js
import '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();
});
然后在终端运行npm run test或jest。将会输出:
PASS __tests__\PostArea_test.js (6.657s)
√ renders correctly (5553ms)
› 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.198s
Ran all test suites.
准备阶段
react-native init
命令行创建的rn项目,并且你的rn版本在0.38以上,则无需安装了。不太清楚的话就看一下package.json
文件中是否包含以下代码:如果没有就安装一下
npm i jest --save-dev
,并把上述代码添加到package.json
文件的对应位置。npm run test
测试一下jest是否配置成功。但我们没有写测试用例,终端会打印no tests found
。这时就配置完成了。快照测试
写一个组件
在项目根目录下找到
__test__
文件夹,现在,让我们使用React的测试渲染器和Jest的快照功能来与组件进行交互,并捕获呈现的输出并创建一个快照文件。然后在终端运行
npm run test
或jest
。将会输出:同时,在test文件夹下会输出一个文件,即为生成的快照。
修改源文件
在下一次运行测试的时候,呈现的输出将与之前创建的快照进行比较。快照应该和代码一起提交。当快照测试失败的时候,就需要检查是否有意或无意的更改。如果是和预期中的变化一样,调用
jest -u
来覆盖当前的快照。我们来更改一下原来的代码:把第二行
<Text>
的字号改为14.这时,我们再运行
jest
。这时终端将会抛出错误,并指出了错误位置 。因为这段代码是我们有意改的,这时运行
jest -u
,快照被覆盖。再执行jest
则不会报错了~