当前位置:网站首页>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 ;
边栏推荐
- What is the most practical gift for Tanabata? A gift that will never go wrong is worth buying
- ---栈&队列---
- Leetcode brush questions diary sword finger offer II 047. Binary tree pruning
- RayMarching realizes volume light rendering
- Optimization ideas from ordinary query commodities to highly concurrent query commodities
- [dynamic planning -- the best period for buying and selling stocks series 3]
- 如何描述一个BUG以及BUG级别的定义、生命周期
- Centos7 deploy MySQL database server
- Yapi vulnerability hanging horse program chongfu.sh processing
- HDU-5783 Divide the Sequence(贪心水题)
猜你喜欢

Personal understanding of Chinese remainder theorem

archery数据库审核平台部署

Dynamic memory management function of C language

Explain in detail

AQS之semaphore源码分析

MySQL主从

AQS之ReentrantLock源码解析

Redis implementation of distributed lock and analysis of the main process of redismission distributed lock

技术分享 | 使用postman发送请求

Everything you don't know about time complexity is here
随机推荐
HDU-5805-NanoApe Loves Sequence(思维题)
KVM热迁移
技术分享 | 如何模拟真实使用场景?mock 技术来帮你
What is the good brand of air conduction Bluetooth headset and the best brand recommendation of air conduction headset
Two dimensional array practice: spiral matrix
NIO示例
MySQL常用命令
技术分享 | 接口测试价值与体系
HDU-1159-CommonSubsequence(LCS最长公共子序列)
Water bottle effect production
cocos2d-x 学习笔记——瓦片地图TiledMap
HDU-5806-NanoApeLovesSequenceⅡ(尺取法)
数组转链表
什么是线性表?
Everything you don't know about time complexity is here
网络通信及TCP/IP协议
SSAO by computer shader (II)
Initializingbean interface and examples
What kind of air conduction Bluetooth headset with good configuration is recommended
如何描述一个BUG以及BUG级别的定义、生命周期