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

tip:
- -
no;不使用ts,使用jest.config.js作為jest的配置文件; - -
jsdom;使用jsdom作為測(cè)試環(huán)境(jsdom:一個(gè)類似瀏覽器的環(huán)境,項(xiàng)目是運(yùn)行在瀏覽器的,需要在瀏覽器dom環(huán)境下測(cè)試); - -
yes;是否添加測(cè)試報(bào)告; - -
babel;使用babel提供的測(cè)試報(bào)告(官網(wǎng)說(shuō)明v8仍處于試驗(yàn)階段,需node14以上使用,效果未知,不穩(wěn)定,因此選用babel);
3. 安裝jsdom環(huán)境
- jest 28及以上版本不再內(nèi)置jsdom插件,需要單獨(dú)安裝
- 安裝官方eslint插件
npm i jest-environment-jsdom eslint-plugin-jest eslint-import-resolver-typescript jest-canvas-mock -D
4. 創(chuàng)建test目錄
在項(xiàng)目根目錄下創(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',
},
};
配置測(cè)試用例的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',
},
},
],
};
代碼覆蓋率報(bào)告無(wú)需加入git版本管理,將test/coverage目錄追加至.gitignore
... # Unit test / coverage reports test/coverage
tsconfig.json中配置路徑別名
5. 愉快地開(kāi)始單元測(cè)試
在 test/__test__ 目錄下新增自己模塊的單元測(cè)試目錄及文件,開(kāi)始單元測(cè)試代碼編寫
文件命名規(guī)范: *.test.ts
6. 總結(jié) - 踩坑記錄
- 默認(rèn)preset為babel-jest,由于 Babel 對(duì) Typescript 的支持是通過(guò)代碼轉(zhuǎn)換(Transpilation)實(shí)現(xiàn)的,而 Jest 在運(yùn)行時(shí)并不會(huì)對(duì)你的測(cè)試用例做類型檢查。 因此建議安裝ts-jest來(lái)開(kāi)啟此功能
- 主要是在配置tsconfig.json路徑別名時(shí)花費(fèi)了大量時(shí)間,處理ts的報(bào)錯(cuò)以及eslint的報(bào)錯(cuò)問(wèn)題;
- 以上配置的路徑別名只需在tsconfig.json一處配置,隨處可用,包括ts、eslint、jest都能讀取同一個(gè)別名配置;
- 另外對(duì)于webpack的別名配置,網(wǎng)上也有讀取tsconfig配置的方案;
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
原生JavaScript實(shí)現(xiàn)的簡(jiǎn)單放大鏡效果示例
這篇文章主要介紹了原生JavaScript實(shí)現(xiàn)的簡(jiǎn)單放大鏡效果,涉及javascript事件響應(yīng)及頁(yè)面元素屬性動(dòng)態(tài)操作相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2018-02-02
微信小程序?qū)崿F(xiàn)點(diǎn)贊業(yè)務(wù)
這篇文章主要為大家詳細(xì)介紹了微信小程序?qū)崿F(xiàn)點(diǎn)贊業(yè)務(wù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-02-02
解決layui中onchange失效以及form動(dòng)態(tài)渲染失效的問(wèn)題
今天小編就為大家分享一篇解決layui中onchange失效以及form動(dòng)態(tài)渲染失效的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-09-09
js實(shí)現(xiàn)無(wú)刷新監(jiān)聽(tīng)URL的變化示例代碼詳解
這篇文章主要介紹了js如何無(wú)刷新監(jiān)聽(tīng)URL的變化,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06
推薦幾個(gè)不錯(cuò)的console調(diào)試技巧實(shí)現(xiàn)
這篇文章主要介紹了推薦幾個(gè)不錯(cuò)的console調(diào)試技巧實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12
原生js驗(yàn)證簡(jiǎn)潔注冊(cè)登錄頁(yè)面
這篇文章主要為大家詳細(xì)介紹了原生js驗(yàn)證簡(jiǎn)潔美觀注冊(cè)登錄頁(yè)面的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-12-12

