当前位置:网站首页>Installation and configuration of unit test framework jest with typescript
Installation and configuration of unit test framework jest with typescript
2022-07-28 06:51:00 【__ Simon】
Install and configure Jest Unit test environment
Step by step guide
Portal :Jest - Quick start
1. install jest:
npm i jest ts-jest @types/jest -D
2. initialization :
npx jest --init
Select as shown in the figure 
tip:
- no; Don't use ts, Use jest.config.js As jest Configuration file for ;
- jsdom; Use jsdom As a test environment (jsdom: A browser like environment , The project is running in the browser , Need to be in the browser dom Test in the environment );
- yes; Whether to add test report ;
- babel; Use babel Test report provided ( Website shows v8 Still in the experimental stage , Need to be node14 Above use , The effect is unknown , unstable , So choose babel);
3. install jsdom Environmental Science :
- jest 28 And above versions are no longer built-in jsdom plug-in unit , Separate installation required
- Install official eslint plug-in unit :
npm i jest-environment-jsdom eslint-plugin-jest eslint-import-resolver-typescript jest-canvas-mock -D
4. establish test Catalog
Create... In the project root directory test Catalog , And then in test Create __mocks and __tests__ Catalog , establish .eslintrc.js and tsconfig.json file 
attach : Configuration example
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',
},
};
Configure test cases eslint The rules /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',
},
},
],
};
Code coverage reports do not need to be included git version management , take test/coverage Directory appended to .gitignore
...
# Unit test / coverage reports
test/coverage
tsconfig.json Configure path aliases
5. Start unit testing happily :
stay test/__test__ Add your own module unit test directory and files under the directory , Start unit test code writing
File naming conventions : *.test.ts
6. summary - Record on pit :
- Default preset by
babel-jest, becauseBabelYesTypescriptIs supported by transcoding (Transpilation) Realized , and Jest Type checking of your test cases is not done at runtime . Therefore, it is recommended to install ts-jest To enable this function - Mainly in configuration
tsconfig.jsonPath alias takes a lot of time , Handle ts Error reporting and eslint The problem of error reporting ; - The path alias configured above only needs to be in
tsconfig.jsonOne configuration , used anywhere , Include ts、eslint、jest Can read the same alias configuration ; - In addition to webpack Alias configuration for , There are also readings on the Internet tsconfig Configuration scheme ;
边栏推荐
猜你喜欢

Prometheus monitoring Nacos

redis缓存设计与性能优化

mongoDB复制集及分片集群

Dynamic memory management function of C language

Water bottle effect production

Graphic pipeline foundation (I)

QGraphicsView提升为QChartView

Mysql-8.0.17-winx64 (additional Navicat) manual configuration version installation

Lancher deployment practice

Analysis of cyclicbarrier source code of AQS
随机推荐
InitializingBean接口及示例
技术分享 | 实战详解接口测试请求方式Get、post
Graphic pipeline foundation (part outside)
redis实现分布式锁思路及redission分布式锁主流程分析
网络通信及TCP/IP协议
mongoDB快速入门
How to store floating point data in memory
[the beginning of self redemption]
File operation in C language
[untitled]
网络——数据链路层
代码整洁之道(二)
OSI七层模型
NIO示例
redis缓存设计与性能优化
Brief analysis of order transaction
Rain Scene Effect (I)
Leetcode skimming diary sword finger offer II 050. sum of downward path nodes
Source code analysis of countdownlatch of AQS
How about air conduction Bluetooth headset? It's the most worthwhile air conduction headset to start with