單元測試框架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和HTML DOM的區(qū)別與聯(lián)系及Javascript和DOM的關(guān)系
這篇文章主要介紹了JavaScript和HTML DOM的區(qū)別與聯(lián)系及Javascript和DOM的關(guān)系的相關(guān)資料,需要的朋友可以參考下2015-11-11
javascript charAt() arr[i]數(shù)組實例代碼
實例區(qū)別一下charAt()和arr[i].toString()的使用方法2008-08-08
javascript typeof的用法與typeof運算符介紹[詳細]
下面是對于typeof運算符的詳細介紹跟typeof的一些用法,分析,學(xué)習(xí)typeof的朋友,看完了,這篇應(yīng)該能有所收獲。2008-10-10
js嵌套的數(shù)組扁平化:將多維數(shù)組變成一維數(shù)組以及push()與concat()區(qū)別的講解
今天小編就為大家分享一篇關(guān)于js嵌套的數(shù)組扁平化:將多維數(shù)組變成一維數(shù)組以及push()與concat()區(qū)別的講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-01-01
typescript在node.js下使用別名(paths)無效的問題詳解
這篇文章主要給大家介紹了關(guān)于typescript在node.js下使用別名(paths)無效問題的相關(guān)資料,文中通過圖文以及示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2022-07-07

