[note] Jest 筆記
keywords: test
, test-driven development
, TDD
- Jest @ Official Doc
npx jest --showConfig # 檢視設定
npx jest -- Checkbox # 測試檔名包含 Checkbox 的檔案
npx jest --coverage # 顯示全部的測試覆蓋率
npx jest --collectCoverageFrom="utils/**/*.{js,jsx,ts,tsx}" # 檢視某一 glob 底下的測試覆蓋率
安裝與設定
$ npm install jest --save-dev
在 package.json
中將 test
的指令改成:
// package.json
"scripts": {
"test": "jest" // --watch, --watchAll
},
預設情況下,Jest 會自動去找:
__tests__
資料夾內的.js
,.jsx
,.ts
,.tsx
- 以
.test
或.spec
結尾的檔案,例如,Component.test.js
orComponent.spec.js
預設的情況下,jest
會去找專案資料夾中的 tests
資料夾:
$ mkdir __tests__
執行測試:
$ npm test -- --coverage # --coverage 會顯示覆蓋率
Jest Configuration
Jest Configuration @ official Doc
在 Jest 中使用 Babel (Import)
Using Babel @ Jest > Getting Started
預設的情況下,Jest 是在 Node 環境下執行,在 ESModule 還沒於 Node 環境普遍被支援前,可以使用 Babel。
安裝 babel 相關套件
$ npm install babel-jest @babel/core @babel/preset-env -D
新增設定檔 babel.config.js
// babel.config.js
module.exports = {
presets: [
[
'@babel/preset-env',
{
targets: {
node: 'current',
},
},
],
],
};
檢視測試覆蓋率
檢視測試覆蓋率有兩種方式,第一種是透過指令:
$ npm test -- --coverage # --coverage 會顯示覆蓋率
第二種是在 package.json
中設定:
// package.json
"scripts": {
"test": "jest"
},
"jest": {
"collectCoverage": true
},
或者:
// package.json
"scripts": {
"test": "jest --coverage"
},
基本語法
官方文件
Globals @ Jest
在 Jest 中,一個基本的測試會長這樣:
- Test Suite:被
describe()
包起來的部分 - Test Case:被
test()
包起來的部分
describe('here is test suite', () => {
test('here is test case', () => {
/* here is assertions */
});
test.todo('...');
test.skip('here is test case', () => {
/* assertions */
});
test.only('here is test case', () => {
/* assertions */
});
test.failing('here is test case', () => {
/* assertions */
});
// Vitest 的話是叫 fails
test.fails('here is test case', () => {
/* assertions */
});
});
使用 test 或 it?
在 Jest 中,test
和 it
是一樣的意思,自己選擇喜歡用的那個即可。