Jest單元測(cè)試

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.jspath/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)行 按鈕即可.

[WebStorm增加Jest函數(shù)補(bǔ)全提示]

[WebStorm – Preferences – Languages & Frameworks – JavaScript – Libraries, 點(diǎn)擊 Download 然后找到列表頁中的 Jest, 然后點(diǎn)擊 Download and Install.]

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,725評(píng)論 25 709
  • React Native優(yōu)秀博客,以及優(yōu)秀的Github庫列表(很多英文資料源自于[awesome-react-n...
    董董董董董董董董董大笨蛋閱讀 11,003評(píng)論 4 162
  • 十八大以來我們進(jìn)入了新時(shí)代,在新時(shí)代我們所有人共同目標(biāo)是實(shí)現(xiàn)中華民族偉大復(fù)興的中國夢(mèng)。這個(gè)夢(mèng)從1840年鴉片...
    青之心路閱讀 339評(píng)論 0 1
  • 星期天來到了這一天正好是奶奶的生日。奶奶喜歡吃鯽魚,爸爸買回來了兩條鯽魚, 媽媽一看,問:“ 你怎么買了兩條...
    極光落日閱讀 309評(píng)論 2 1
  • 風(fēng) 虛掩在岸上 水 被刺的支離破碎 時(shí)而痛的直在瀑布里打滾 蕩出不規(guī)則的漣漪 藻荇 摒棄了鯽鯉 偷偷趕來湊熱鬧 浪...
    木云yang閱讀 537評(píng)論 2 2

友情鏈接更多精彩內(nèi)容