基本用法
匹配器
-
toBe
test('two plus two is four', () => { expect(2 + 2).toBe(4); });
toEqual (检查两个对象或集合是否完全相等)
toBeNull、toBeUndefined、toBeDefined、toBeTruthy、toBeFalsy
toBeGreaterThan、toBeLessThan
toBeCloseTo(浮点数判断)
-
toMatch(字符串判断)
test('there is no I in team', () => { expect('team').not.toMatch(/I/); });
toContain (集合判断)
-
toThrow
function compileAndroidCode() { throw new Error('you are using the wrong JDK'); } test('compiling android goes as expected', () => { expect(() => compileAndroidCode()).toThrow(); expect(() => compileAndroidCode()).toThrow(Error); // You can also use the exact error message or a regexp expect(() => compileAndroidCode()).toThrow('you are using the wrong JDK'); expect(() => compileAndroidCode()).toThrow(/JDK/); });
测试异步代码
-
done()
test('the data is peanut butter', done => { function callback(data) { try { expect(data).toBe('peanut butter'); done(); } catch (error) { done(error); } } fetchData(callback); }); // 如果未调用done,则默认会输出‘Error: thrown: "Exceeded timeout of 5000 ms for a test.’,想要详细的错误信息,可以使用try/catach
-
promise
test('the data is peanut butter', () => { return fetchData().then(data => { expect(data).toBe('peanut butter'); }); }); test('the fetch fails with an error', () => { expect.assertions(1); return fetchData().catch(e => expect(e).toMatch('error')); }); // return Promise,jest 会自动处理resolve 和 reject 情况
-
.resolves/.rejects
test('the data is peanut butter', () => { return expect(fetchData()).resolves.toBe('peanut butter'); }); test('the fetch fails with an error', () => { return expect(fetchData()).rejects.toMatch('error'); });
-
async/await
test('the data is peanut butter', async () => { const data = await fetchData(); expect(data).toBe('peanut butter'); }); test('the fetch fails with an error', async () => { expect.assertions(1); try { await fetchData(); } catch (e) { expect(e).toMatch('error'); } });
-
combine async/await with .resolves/.rejects
test('the data is peanut butter', async () => { await expect(fetchData()).resolves.toBe('peanut butter'); }); test('the fetch fails with an error', async () => { await expect(fetchData()).rejects.toMatch('error'); });
初始化和销毁
beforeEach / afterEach
beforeAll / afterAll
-
describe
/*Jest executes all describe handlers in a test file before it executes any of the actual tests. This is another reason to do setup and teardown inside before* and after* handlers rather than inside the describe blocks. Once the describe blocks are complete, by default Jest runs all the tests serially in the order they were encountered in the collection phase, waiting for each to finish and be tidied up before moving on.*/ describe('outer', () => { console.log('describe outer-a'); describe('describe inner 1', () => { console.log('describe inner 1'); test('test 1', () => { console.log('test for describe inner 1'); expect(true).toEqual(true); }); }); console.log('describe outer-b'); test('test 1', () => { console.log('test for describe outer'); expect(true).toEqual(true); }); describe('describe inner 2', () => { console.log('describe inner 2'); test('test for describe inner 2', () => { console.log('test for describe inner 2'); expect(false).toEqual(false); }); }); console.log('describe outer-c'); }); // describe outer-a // describe inner 1 // describe outer-b // describe inner 2 // describe outer-c // test for describe inner 1 // test for describe outer // test for describe inner 2
模拟函数
-
什么是mock functions
Mock functions allow you to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated with
new
, and allowing test-time configuration of return values.The goal for mocking is to replace something we don’t control with something we do
mock函数提供的特性如下:
- 捕获调用
- 设置返回值
- 改变实现
-
创建模拟函数
// 通过jest.fn() 创建模拟函数,可以测试函数调用状态和调用参数等信息 function forEach(items, callback) { for (let index = 0; index < items.length; index++) { callback(items[index]); } } const mockCallback = jest.fn(x => 42 + x); forEach([0, 1], mockCallback); // The mock function is called twice expect(mockCallback.mock.calls.length).toBe(2); // The first argument of the first call to the function was 0 expect(mockCallback.mock.calls[0][0]).toBe(0); // The first argument of the second call to the function was 1 expect(mockCallback.mock.calls[1][0]).toBe(1); // The return value of the first call to the function was 42 expect(mockCallback.mock.results[0].value).toBe(42);
-
模拟返回值
const myMock = jest.fn(); console.log(myMock()); // > undefined myMock.mockReturnValueOnce(10).mockReturnValueOnce('x').mockReturnValue(true); console.log(myMock(), myMock(), myMock(), myMock()); // > 10, 'x', true, true
-
模拟模块
users.js --------------------------------------------------- import axios from 'axios'; class Users { static all() { return axios.get('/users.json').then(resp => resp.data); } } export default Users; --------------------------------------------------- test.js --------------------------------------------------- import axios from 'axios'; import Users from './users'; jest.mock('axios'); test('should fetch users', () => { const users = [{name: 'Bob'}]; const resp = {data: users}; axios.get.mockResolvedValue(resp); // or you could use the following depending on your use case: // axios.get.mockImplementation(() => Promise.resolve(resp)) return Users.all().then(data => expect(data).toEqual(users)); });
-
jest.spyOn()
jest.mock()通常无法访问到原始实现,spyOn可以修改原始实现,且稍后可以恢复
-
测试覆盖率
yarn test --coverage
Stats
为语句测试覆盖率。Branch
为条件分支测试覆盖率。Funcs
为函数覆盖率。Lines
为行覆盖率。Uncovered Line
为未覆盖的行号
快照
test('renders correctly', () => {
const tree = renderer.create(<He/>).toJSON();
expect(tree).toMatchSnapshot();
});
错误集锦
ES6 support
-
FAIL src/__tests__/navigation.test.ts ● Test suite failed to run Jest encountered an unexpected token This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript. By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules". Here's what you can do: • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config. • If you need a custom transformation specify a "transform" option in your config. • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option. You'll find more details and examples of these config options in the docs: https://jestjs.io/docs/en/configuration.html Details: /Users/jyurek/Development/react-navigation-error-replication/node_modules/react-navigation-stack/dist/index.js:2 import { Platform } from 'react-native'; ^ SyntaxError: Unexpected token { 2 | import {ExampleScreen} from './screens/ExampleScreen'; 3 | > 4 | const Navigation = createStackNavigator({ | ^ 5 | ExampleScreen: { 6 | screen: ExampleScreen, 7 | }, at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:451:17) at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:493:19) at Object.get createStackNavigator [as createStackNavigator] (node_modules/react-navigation/src/react-navigation.js:107:12) at Object.<anonymous> (src/navigation.ts:4:20)
此类问题为native module使用了ES语法,而jest默认是不支持ES语法的。解决方法是使用babel, 自定义babel配置, jest自动使用babel做语法转换。但是又因为jest默认会忽略'node_modules', 即'node_modules'下的内容不会做语法转换。解决方法为在jest配置中添加‘transformIgnorePatterns’属性:
{ "transformIgnorePatterns": [ "node_modules/(?!(react-native|react-native-button)/)" ] }
mock NativeModule
-
Test suite failed to run [@RNC/AsyncStorage]: NativeModule: AsyncStorage is null. To fix this issue try these steps: • Run `react-native link @react-native-async-storage/async-storage` in the project root. • Rebuild and restart the app. • Run the packager with `--reset-cache` flag. • If you are using CocoaPods on iOS, run `pod install` in the `ios` directory and then rebuild and re-run the app. • If this happens while testing with Jest, check out docs how to integrate AsyncStorage with it: https://react-native-async-storage.github.io/async-storage/docs/advanced/jest If none of these fix the issue, please open an issue on the Github repository: https://github.com/react-native-async-storage/react-native-async-storage/issues
此类问题为需要mock对应模块,一般对应模块文档会有相关mock实现
React is not defined
-
React is not defined ReferenceError: React is not defined at Object.<anonymous> (/Users/daniel/Desktop/EcovacsHomeRN/__tests__/RobotMsgTabPages.test.js:6:39) at Promise.then.completed (/Users/daniel/Desktop/EcovacsHomeRN/node_modules/jest-circus/build/utils.js:391:28) at new Promise (<anonymous>) at callAsyncCircusFn (/Users/daniel/Desktop/EcovacsHomeRN/node_modules/jest-circus/build/utils.js:316:10) at _callCircusTest (/Users/daniel/Desktop/EcovacsHomeRN/node_modules/jest-circus/build/run.js:218:40) at processTicksAndRejections (node:internal/process/task_queues:96:5) at _runTest (/Users/daniel/Desktop/EcovacsHomeRN/node_modules/jest-circus/build/run.js:155:3) at _runTestsForDescribeBlock (/Users/daniel/Desktop/EcovacsHomeRN/node_modules/jest-circus/build/run.js:66:9) at run (/Users/daniel/Desktop/EcovacsHomeRN/node_modules/jest-circus/build/run.js:25:3) at runAndTransformResultsToJestFormat (/Users/daniel/Desktop/EcovacsHomeRN/node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapterInit.js:170:21)
此情况一般为在用
react-test-renderer
做组件测试时,在import renderer from 'react-test-renderer';
之前需要import React from "react";
nativeBridge
-
Cannot read property 'rnConnection' of undefined TypeError: Cannot read property 'rnConnection' of undefined
在测试文件中mock,
NativeModules.Bridge = {rnConnection: jest.fn()}
SyntaxError
-
SyntaxError: /Users/daniel/Desktop/EcovacsHomeRN/node_modules/@react-native/polyfills/error-guard.js: Unexpected token, expected "," (51:22) 49 | _globalHandler && _globalHandler(error, true); 50 | }, > 51 | applyWithGuard<TArgs: $ReadOnlyArray<mixed>, TOut>( | ^ 52 | fun: Fn<TArgs, TOut>, 53 | context?: ?mixed, 54 | args?: ?TArgs,
此为babel配置了
@babel/plugin-syntax-typescript
插件导致babel只做TS语法解析,而不做语法转换,在jest组件测试会报语法错误。解决方案为使用@babel/plugin-transform-typescript
或者@babel/preset-typescript
同时支持语法解析和转化.文档地址:https://babel.dev/docs/en/babel-plugin-syntax-typescript
小试牛刀
-
测试组件方法调用
import React from "react"; import RobotMsgTabPages from "../js/AppCommon/robot/RobotMessage/RobotMsgTabPages"; import renderer from 'react-test-renderer'; import MessageCenterHomePage from "../js/AppCommon/messageCenter/MessageCenterHomePage"; import {NativeModules} from "react-native"; import RobotEmptyView from "../js/AppCommon/robot/RobotMessage/CommonComponent/RobotEmptyView"; import {SwipeListView} from "react-native-swipe-list-view"; it('should ropRobotTabMsgList callback', function () { const state = {routeName : '', params: {did : '13',title : '123', hasUnreadMsg : true,item : '',changeUnread : true}} const getParam = params => {return true}; const addListener = (params,callback) => {} const component = renderer.create(<RobotMsgTabPages navigation={{"state":state, "getParam":getParam, "addListener" : addListener}}/>).root; const swipeListView = component.findByType(RobotEmptyView); console.log(swipeListView.props.onPress) });
-
测试接口调用
import { ropRobotProductMsgList} from '../js/InternalModule/api/MessageCenterApi' // import {fetch} from "@react-native-community/netinfo"; // jest.mock('../js/InternalModule/api/MessageCenterApi') beforeAll(() => { RopConstants.iotServerUrl = "dadadadad" }) test('mock modules', async () => { // fetch.mockResolvedValue('ddad'); // fetch.mockReturnValue('dadaad'); // ropRobotProductMsgList.mockImplementation(() => { // return new Promise((resolve, reject) => { // reject('dadaad') // }); // }) await expect(ropRobotProductMsgList({'a' : 'ddaq'})).rejects.toEqual('dadaad'); });