[TOC]
Introducing Jest
Delightful JavaScript Testing.
簡單說Jest就是一個 JS 測試框架
項目主頁
http://facebook.github.io/jest/
為什么選擇 Jest
Jest 是 Facebook 出品的一個測試框架,相對其他測試框架,其一大特點就是就是內置了常用的測試工具,比如自帶斷言、測試覆蓋率工具,實現了開箱即用。
而作為一個面向前端的測試框架, Jest 可以利用其特有的快照測試功能,通過比對 UI 代碼生成的快照文件,實現對 React 等常見框架的自動測試。
此外, Jest 的測試用例是并行執行的,而且只執行發生改變的文件所對應的測試,提升了測試速度。目前在 Github 上其 star 數已經破萬;而除了 Facebook 外,業內其他公司也開始從其它測試框架轉向 Jest ,比如 Airbnb 的嘗試 ,相信未來 Jest 的發展趨勢仍會比較迅猛。
適用范圍
不僅能測試RN,甚至能測試Vue:http://facebook.github.io/jest/docs/en/testing-frameworks.html
Although Jest may be considered a React-specific test runner, in fact it is a universal testing platform, with the ability to adapt to any JavaScript library or framework.
特性
Easy Setup
完整又輕松的JS測試方案,安裝、設置簡單,與工程代碼隔離。
Instant Feedback
多線程測試,即刻的測試結果反饋。只運行那些和更改了的文件有關的測試,提高測試速度。
Snapshot
還有一個奇妙的功能叫snapshot:對React trees(VDOM) 進行檢測,比對UI代碼分析改動。
安裝
Install Jest using npm
:
npm install --save-dev jest
Or via yarn
:
yarn add --dev jest
使用
Jest 內部使用了 Jasmine 2 來進行測試,故其用例語法與 Jasmine 相同。
First, create a sum.js
file:
function sum(a, b) {
return a + b;
}
module.exports = sum;
Then, create a file named sum.test.js
. This will contain our actual test:
const sum = require('./sum');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
Add the following section to your package.json
:
{
"scripts": {
"test": "jest"
}
}
Finally, run npm test
and Jest will print this message:
PASS ./sum.test.js
? adds 1 + 2 to equal 3 (5ms)
You just successfully wrote your first test using Jest!
在上述代碼中,expect(sum(1, 2))返回一個“期望”對象,通常我們不會對這個期望對象進行匹配,而是由matchers完成,在這里.toBe(3)便是這個matchers,當Jest運行時,它會跟蹤所有失敗的matchers以便打印正確的錯誤信息給我們。
toBe使用 === 來測試全等于,如果我們想檢查一個對象object中的值,使用toEqual來替代,toEqual遞歸遍歷檢查對象或數組里的每一個領域。
To learn about the other things that Jest can test, seeUsing Matchers.
測試覆蓋率
Jest 內置了測試覆蓋率工具 istanbul,要開啟,可以直接在命令中添加 --coverage
參數,或者在 package.json 文件進行更詳細的配置。
運行 istanbul 除了會再終端展示測試覆蓋率情況,還會在項目下生產一個 coverage 目錄,內附一個測試覆蓋率的報告,讓我們可以清晰看到分支的代碼的測試情況。
Snapshot Test
針對前端框架的測試, Jest 的一大特色就是提供了快照測試功能。首次運行快照測試,會讓 UI 框架生產一個可讀的快照,再次測試時便會通過比對快照文件和新 UI 框架產生的快照判斷測試是否通過。
import 'react-native';
import React from 'react';
import App from '../App';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<App />
).toJSON();
expect(tree).toMatchSnapshot();
});
運行測試即可生成一個快照文件。這個文件以可讀的形式展示出了React渲染出的DOM結構。相比于肉眼觀察效果,快照測試直接由Jest進行比對、速度更快。
在你下一次run tests的時候,rendered output 會和先前生成的快照文件進行對比。因此快照文件應該被包含于git追蹤。
當快照測試失敗時,你需要去判定這是你需要的修改還是無意中改動的。若是你需要的修改,調用 jest -u
去更新快照。