單元測試框架Jest搭配TypeScript的安裝與配置方式
為項目安裝并配置Jest單元測試環(huán)境
分步指南
傳送門:Jest - 快速入門
1. 安裝jest
npm i jest ts-jest @types/jest -D
2. 初始化
npx jest --init
按照圖中所示選擇

tip:
- -
no;不使用ts,使用jest.config.js作為jest的配置文件; - -
jsdom;使用jsdom作為測試環(huán)境(jsdom:一個類似瀏覽器的環(huán)境,項目是運行在瀏覽器的,需要在瀏覽器dom環(huán)境下測試); - -
yes;是否添加測試報告; - -
babel;使用babel提供的測試報告(官網(wǎng)說明v8仍處于試驗階段,需node14以上使用,效果未知,不穩(wěn)定,因此選用babel);
3. 安裝jsdom環(huán)境
- jest 28及以上版本不再內(nèi)置jsdom插件,需要單獨安裝
- 安裝官方eslint插件
npm i jest-environment-jsdom eslint-plugin-jest eslint-import-resolver-typescript jest-canvas-mock -D
4. 創(chuàng)建test目錄
在項目根目錄下創(chuàng)建test目錄,然后在test下創(chuàng)建__mocks和__tests__目錄,創(chuàng)建.eslintrc.js和tsconfig.json文件

附:配置示例
jest.config.js
/*
* For a detailed explanation regarding each configuration property, visit:
* https://jestjs.io/docs/configuration
*/
const { pathsToModuleNameMapper } = require('ts-jest');
const { compilerOptions } = require('./tsconfig.json');
module.exports = {
// A preset that is used as a base for Jest's configuration
preset: 'ts-jest',
// The test environment that will be used for testing
testEnvironment: 'jsdom',
// The paths to modules that run some code to configure or set up the testing environment before each test
setupFiles: ['jest-canvas-mock'],
// Automatically clear mock calls, instances, contexts and results before every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
collectCoverage: true,
// The directory where Jest should output its coverage files
coverageDirectory: 'test/coverage',
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
// rootDir: __dirname,
// An array of file extensions your modules use
moduleFileExtensions: ['ts', 'js'],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, {
prefix: '<rootDir>/',
}),
// The glob patterns Jest uses to detect test files
testMatch: ['<rootDir>/test/__tests__/**/*.test.ts'],
// A map from regular expressions to paths to transformers
transform: {
'^.+\\.ts$': 'ts-jest',
},
};
配置測試用例的eslint規(guī)則
/test/.eslintrc.js
module.exports = {
extends: ['../.eslintrc.js'],
settings: {
'import/resolver': {
typescript: {
alwaysTryTypes: true, // always try to resolve types under `<root>@types` directory even it doesn't contain any source code, like `@types/unist`
// Choose from one of the "project" configs below or omit to use <root>/tsconfig.json by default
// use <root>/path/to/folder/tsconfig.json
project: 'tsconfig.json',
},
},
},
plugins: ['jest'],
overrides: [
// unit-tests
{
files: ['**/__tests__/**'],
rules: {
'jest/no-disabled-tests': 'warn',
'jest/no-focused-tests': 'error',
'jest/no-identical-title': 'error',
'jest/prefer-to-have-length': 'warn',
'jest/valid-expect': 'error',
},
},
],
};
代碼覆蓋率報告無需加入git版本管理,將test/coverage目錄追加至.gitignore
... # Unit test / coverage reports test/coverage
tsconfig.json中配置路徑別名
5. 愉快地開始單元測試
在 test/__test__ 目錄下新增自己模塊的單元測試目錄及文件,開始單元測試代碼編寫
文件命名規(guī)范: *.test.ts
6. 總結(jié) - 踩坑記錄
- 默認preset為babel-jest,由于 Babel 對 Typescript 的支持是通過代碼轉(zhuǎn)換(Transpilation)實現(xiàn)的,而 Jest 在運行時并不會對你的測試用例做類型檢查。 因此建議安裝ts-jest來開啟此功能
- 主要是在配置tsconfig.json路徑別名時花費了大量時間,處理ts的報錯以及eslint的報錯問題;
- 以上配置的路徑別名只需在tsconfig.json一處配置,隨處可用,包括ts、eslint、jest都能讀取同一個別名配置;
- 另外對于webpack的別名配置,網(wǎng)上也有讀取tsconfig配置的方案;
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
原生JavaScript實現(xiàn)的簡單放大鏡效果示例
這篇文章主要介紹了原生JavaScript實現(xiàn)的簡單放大鏡效果,涉及javascript事件響應(yīng)及頁面元素屬性動態(tài)操作相關(guān)實現(xiàn)技巧,需要的朋友可以參考下2018-02-02
解決layui中onchange失效以及form動態(tài)渲染失效的問題
今天小編就為大家分享一篇解決layui中onchange失效以及form動態(tài)渲染失效的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-09-09
js實現(xiàn)無刷新監(jiān)聽URL的變化示例代碼詳解
這篇文章主要介紹了js如何無刷新監(jiān)聽URL的變化,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06
推薦幾個不錯的console調(diào)試技巧實現(xiàn)
這篇文章主要介紹了推薦幾個不錯的console調(diào)試技巧實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12

