Jest是facebook出品的JavaScript单元测试软件.
最常用的代码: expect(变量).toEqual(期待值);
示例代码:
import sum from '../_study/sum';
// const sum = require('./sum');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
test('判断2+4不等于5', () => {
expect(sum(2, 4)).not.toBe(5);
});
[参考资料]
中文文档:
http://facebook.github.io/jest/docs/zh-Hans/getting-started.html
官方示例代码:
https://github.com/facebook/jest/tree/master/examples
API 接口列表: http://facebook.github.io/jest/docs/en/jest-object.html#content
数值比较API: https://facebook.github.io/jest/docs/en/expect.html
初尝 Jest 单元测试: http://imweb.io/topic/592aab6eff03ef1a4ef15c51
Jest官方博客: https://facebook.github.io/jest/blog
https://dev.to/preslavrachev/testing-react-native-applications-part-i-jest
https://stackoverflow.com/questions/40449434/mocking-globals-in-jest
ant design的测试(非常简单): https://github.com/ant-design/ant-design-mobile/blob/master/tests/shared/demoTest.js
https://facebook.github.io/jest/docs/jest-object.html
https://github.com/wheresrhys/fetch-mock
https://www.snip2code.com/Snippet/1682585/Mock-Fetch-with-Jest/
http://www.wheresrhys.co.uk/fetch-mock/api
全栈React: 第25天 使用Enzyme做更好的测试 http://zcfy.cc/article/fullstack-react-better-testing-with-enzyme-3806.html
https://facebook.github.io/react/docs/test-utils.html
快照测试如何对比不同状态下的组件?
[安装命令行工具]
npm install -g jest
[运行测试]
[在 WebStorm中运行]
打开__tests__
中的文件, 点击行号右侧的运行小箭头即可. 或者右键点击, 选择 Run xx.js
[命令行运行]
运行所有测试 (默认):
cd __tests__
jest
运行指定测试, 通过命名规则或者指定文件名:
jest my-test #or
jest path/to/my-test.js
只针对 hg/git 中已修改的文件运行测试 (未提交的文件):
jest -o
运行文件 path/to/fileA.js
和 path/to/fileB.js
的关联测试:
jest --findRelatedTests path/to/fileA.js path/to/fileB.js
Run tests that match this spec name (match against the name in describe
or test
, basically).
jest -t name-of-spec
监视模式运行:
jest --watch #runs jest -o by default
jest --watchAll #runs all tests
监视模式下也可以指定文件名或者路径来集中处理指定组的测试.
[使用npm脚本运行]
在package.json中添加配置项:
"scripts": {
...
"test": "jest",
},
...,
"devDependencies": {
"babel-jest": "19.0.0",
"babel-preset-react-native": "1.9.1",
"jest": "19.0.2",
"react-test-renderer": "15.4.2"
},
"jest": {
"preset": "react-native",
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
"verbose": true,
"collectCoverage": true,
"moduleFileExtensions": [
"js"
],
"globals": {
"__DEV__": true
},
"transform": {
"^.+\\.js$": "babel-jest"
},
"transformIgnorePatterns": [
"node_modules/(?!react-native|react-navigation)/"
]
},
注意下面代码是为了解决ES6语法的库运行时的报错问题.
"transform": { "^.+\\.js$": "babel-jest"}
然后可以运行:
npm test
完整的命令行选项请参考: https://facebook.github.io/jest/docs/cli.html
[延迟判断测试]
有时候某些测试必须等待几个毫秒来执行, 这时候就需要用到延迟判断. 典型的场景如下: App中发起了一次网络请求, 然后根据返回的数据更新了一些状态. 虽然网络请求使用mock会很快, 但是整个执行过程并不是同步的, 究竟多久执行完也是无法确定的, 因此需要稍微延迟一下进行状态判断测试.
// 延迟等待判断的测试, 参考: https://github.com/facebook/jest/issues/42
// 注意done参数一定不要漏掉了
test("takes a long time", function(done) {
// do something
setTimeout(function() {
// run your expectation
expect(0).not.toBe(10);
done();
}, 1000);
});
// 简化等效写法
test('real timer ', (done) => {
setTimeout(function() {
// run your expectation
expect(0).not.toBe(10);
done();
}, 1000);
});
[常见错误及解决]
[import语法不对]
https://stackoverflow.com/questions/43514455/react-nativejestsyntaxerror-unexpected-token-import
[Test suite failed to run Invariant Violation: Native module cannot be null.]
at invariant (node_modules/fbjs/lib/invariant.js:44:7)
at new NativeEventEmitter (node_modules/react-native/Libraries/EventEmitter/NativeEventEmitter.js:32:1)
at Object.<anonymous style="-webkit-font-smoothing: antialiased; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); text-size-adjust: none; box-sizing: border-box;"> (node_modules/react-native/Libraries/Network/NetInfo.js:20:25)</anonymous>
at Object.get NetInfo [as NetInfo] (node_modules/react-native/Libraries/react-native/react-native.js:93:22)
at new NetInfoSingleton (app/util/NetInfoSingleton.js:24:13)
at Object.<anonymous style="-webkit-font-smoothing: antialiased; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); text-size-adjust: none; box-sizing: border-box;"> (app/util/NetInfoSingleton.js:48:25)</anonymous>
参考: https://github.com/facebook/jest/issues/2208
需要mock native的一些行为. 这个导致RN测试比较难做.
[refs测试子组件找不到如何解决?]
Refs are null in Jest snapshot tests with react-test-renderer
https://github.com/facebook/jest/issues/42
解决: 测试之前需要mock一些假的refs代码
let instance = wrapper.instance();
instance.refs = {timerButton: { state: {counting: false}}};
instance._requestSMSCode();
// 使用真正的定时器, 否则异步执行会立即返回, 导致状态判断出错
jest.useRealTimers();
setTimeout(function() {
// run your expectation
expect(instance.state.verifyText).toEqual('需要图形码44');
console.log("instance.state", instance.state);
console.log("instance.refs", instance.refs);
done();
}, 1000);
[代码中import了json资源但是提示访问不到?]
https://github.com/facebook/jest/issues/238
import xxx from '../data/myjson';// myjson.json
出错信息: Cannot find module '../data/myjson' from 'xxxTest.js'
解决: 修改package.json中的jest配置, 加入json扩展名
"moduleFileExtensions": [
"js", "jsx", "json"
]
[mock代码被当做测试执行报错?]
https://github.com/facebook/jest/tree/master/examples/manual-mocks
参考这里的目录结构, __tests__
和 __mocks__
分开存放test.js文件和mock的类.
[WebStorm集成Jest](
[运行单个测试]
打开测试代码, 点击代码测试方法最左侧的向右三角箭头即可运行单个测试.
[运行所有测试]
Run > Edit Configurations, 然后点击 + 号按钮, 类别那里选择 Jest, 默认就会生成一个运行所有Test的Jest任务. 点击工具栏上的 运行 按钮即可.