Jest是facebook出品的JavaScript單元測(cè)試軟件.
最常用的代碼: 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
數(shù)值比較API: https://facebook.github.io/jest/docs/en/expect.html
初嘗 Jest 單元測(cè)試: 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的測(cè)試(非常簡(jiǎn)單): 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做更好的測(cè)試 http://zcfy.cc/article/fullstack-react-better-testing-with-enzyme-3806.html
https://facebook.github.io/react/docs/test-utils.html
快照測(cè)試如何對(duì)比不同狀態(tài)下的組件?
[安裝命令行工具]
npm install -g jest
[運(yùn)行測(cè)試]
[在 WebStorm中運(yùn)行]
打開__tests__中的文件, 點(diǎn)擊行號(hào)右側(cè)的運(yùn)行小箭頭即可. 或者右鍵點(diǎn)擊, 選擇 Run xx.js
[命令行運(yùn)行]
運(yùn)行所有測(cè)試 (默認(rèn)):
cd __tests__
jest
運(yùn)行指定測(cè)試, 通過命名規(guī)則或者指定文件名:
jest my-test #or
jest path/to/my-test.js
只針對(duì) hg/git 中已修改的文件運(yùn)行測(cè)試 (未提交的文件):
jest -o
運(yùn)行文件 path/to/fileA.js 和 path/to/fileB.js的關(guān)聯(lián)測(cè)試:
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
監(jiān)視模式運(yùn)行:
jest --watch #runs jest -o by default
jest --watchAll #runs all tests
監(jiān)視模式下也可以指定文件名或者路徑來集中處理指定組的測(cè)試.
[使用npm腳本運(yùn)行]
在package.json中添加配置項(xiàng):
"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語法的庫運(yùn)行時(shí)的報(bào)錯(cuò)問題.
"transform": { "^.+\\.js$": "babel-jest"}
然后可以運(yùn)行:
npm test
完整的命令行選項(xiàng)請(qǐng)參考: https://facebook.github.io/jest/docs/cli.html
[延遲判斷測(cè)試]
有時(shí)候某些測(cè)試必須等待幾個(gè)毫秒來執(zhí)行, 這時(shí)候就需要用到延遲判斷. 典型的場(chǎng)景如下: App中發(fā)起了一次網(wǎng)絡(luò)請(qǐng)求, 然后根據(jù)返回的數(shù)據(jù)更新了一些狀態(tài). 雖然網(wǎng)絡(luò)請(qǐng)求使用mock會(huì)很快, 但是整個(gè)執(zhí)行過程并不是同步的, 究竟多久執(zhí)行完也是無法確定的, 因此需要稍微延遲一下進(jìn)行狀態(tài)判斷測(cè)試.
// 延遲等待判斷的測(cè)試, 參考: https://github.com/facebook/jest/issues/42
// 注意done參數(shù)一定不要漏掉了
test("takes a long time", function(done) {
// do something
setTimeout(function() {
// run your expectation
expect(0).not.toBe(10);
done();
}, 1000);
});
// 簡(jiǎn)化等效寫法
test('real timer ', (done) => {
setTimeout(function() {
// run your expectation
expect(0).not.toBe(10);
done();
}, 1000);
});
[常見錯(cuò)誤及解決]
[import語法不對(duì)]
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的一些行為. 這個(gè)導(dǎo)致RN測(cè)試比較難做.
[refs測(cè)試子組件找不到如何解決?]
Refs are null in Jest snapshot tests with react-test-renderer
https://github.com/facebook/jest/issues/42
解決: 測(cè)試之前需要mock一些假的refs代碼
let instance = wrapper.instance();
instance.refs = {timerButton: { state: {counting: false}}};
instance._requestSMSCode();
// 使用真正的定時(shí)器, 否則異步執(zhí)行會(huì)立即返回, 導(dǎo)致狀態(tài)判斷出錯(cuò)
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
出錯(cuò)信息: Cannot find module '../data/myjson' from 'xxxTest.js'
解決: 修改package.json中的jest配置, 加入json擴(kuò)展名
"moduleFileExtensions": [
"js", "jsx", "json"
]
[mock代碼被當(dāng)做測(cè)試執(zhí)行報(bào)錯(cuò)?]
https://github.com/facebook/jest/tree/master/examples/manual-mocks
參考這里的目錄結(jié)構(gòu), __tests__和 __mocks__分開存放test.js文件和mock的類.
[WebStorm集成Jest](
[運(yùn)行單個(gè)測(cè)試]
打開測(cè)試代碼, 點(diǎn)擊代碼測(cè)試方法最左側(cè)的向右三角箭頭即可運(yùn)行單個(gè)測(cè)試.
[運(yùn)行所有測(cè)試]
Run > Edit Configurations, 然后點(diǎn)擊 + 號(hào)按鈕, 類別那里選擇 Jest, 默認(rèn)就會(huì)生成一個(gè)運(yùn)行所有Test的Jest任務(wù). 點(diǎn)擊工具欄上的 運(yùn)行 按鈕即可.