当前位置:网站首页>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 ;
边栏推荐
- Graphic pipeline foundation (I)
- Two dimensional array practice: spiral matrix
- 单项链表的创建、遍历以及按要求查找结点
- [dynamic planning -- the best period series for buying and selling stocks]
- Implementation of simple address book in [c language]
- Array solution script
- [dynamic planning -- the best period for buying and selling stocks series 3]
- Scratch command
- InitializingBean接口及示例
- redis实现分布式锁思路及redission分布式锁主流程分析
猜你喜欢

redis缓存设计与性能优化

How to calculate the size of structure, segment and Consortium (common body)

CentOS7部署MySQL数据库服务器

技术分享 | 服务端接口自动化测试, Requests 库的这些功能你了解吗?

SSAO by computer shader (II)

Prometheus monitoring Nacos

Analysis of cyclicbarrier source code of AQS

浅谈Cookie和Session

Water drop effect on umbrella

Which brand of air conduction earphones is better? These four should not be missed
随机推荐
HDU-1159-CommonSubsequence(LCS最长公共子序列)
How to store floating point data in memory
prometheus监控nacos
How to simulate the implementation of strcpy library functions
How to calculate the size of structure, segment and Consortium (common body)
准备开始写博客了
Everything you don't know about time complexity is here
网络——数据链路层
技术分享 | 接口自动化测试中,如何做断言验证?
测试人生 | 二线城市年薪超40W?疫情之下涨薪100% + 是怎么做到的?
网络——传输层(详细版)
SSAO by computer shader (I)
NiO example
cocos2d-x 学习笔记——瓦片地图TiledMap
Leetcode brush question diary sword finger offer II 048. serialization and deserialization binary tree
[C language] string library function introduction and simulation
设计测试用例的方法
MySQL index optimization
iptables防火墙
PKU-2524-Ubiquitous Religions(并查集模板)