当前位置:网站首页>JS note 17: the whole process of jest project configuration of typescript project
JS note 17: the whole process of jest project configuration of typescript project
2022-07-25 07:16:00 【Passing cat 2022】
typescript Project jest The whole process of project configuration
- For existing typescript project
js Series notes
install jest
- Under the project directory , That is to say package.json directory , Access control
>npm install --save-dev jest
# You can also use global jest
> npm install jest -g
- modify package.json, stay scripts Add two lines
"test": "jest", // unit testing
"test-c": "jest --coverage", // Test coverage
then , Under the console , Input npm run test, You can execute jest test
- Generate jest The default configuration ,jest Itself can 0 Configuration and use
# The description of this build configuration comes from :https://blog.csdn.net/u012961419/article/details/123638495
# Generate jest The configuration file
jest --init
# The format of the configuration file ts or js
√ Would you like to use Typescript for the configuration file? ... no
# Test environment node Environmental Science or jsdom Browser environment
√ Choose the test environment that will be used for testing » jsdom (browser-like)
# If you need Jest Collect test coverage reports
√ Do you want Jest to add coverage reports? ... no
# Engine used to count test coverage
# At present, the most stable is babel,v8 Still in the experimental stage , Suggest node v14 Version above use
√ Which provider should be used to instrument code for coverage? » babel
# Whether to clear before each test mock Call and related instances
√ Automatically clear mock calls, instances and results before every test? ... yes
- After completion , Will generate a jest.config.js The configuration file
/* * For a detailed explanation regarding each configuration property, visit: * https://jestjs.io/docs/configuration */
module.exports = {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
// bail: 0,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "C:\\Users\\rex\\AppData\\Local\\Temp\\jest",
// Automatically clear mock calls, instances, contexts and results before every test
// clearMocks: false,
// Indicates whether the coverage information should be collected while executing the test
// collectCoverage: false,
// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,
// The directory where Jest should output its coverage files
// coverageDirectory: undefined,
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "\\\\node_modules\\\\"
// ],
// Indicates which provider should be used to instrument code for coverage
coverageProvider: "v8",
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// The default configuration for fake timers
// fakeTimers: {
// "enableGlobally": false
// },
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "mjs",
// "cjs",
// "jsx",
// "ts",
// "tsx",
// "json",
// "node"
// ],
// 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: {},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
// preset: undefined,
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state before every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state and implementation before every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
// testEnvironment: "jest-environment-node",
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "\\\\node_modules\\\\"
// ],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
// This option allows use of a custom test runner
// testRunner: "jest-circus/runner",
// A map from regular expressions to paths to transformers
// transform: undefined,
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "\\\\node_modules\\\\",
// "\\.pnp\\.[^\\\\]+$"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};
Use typescript
- Install dependency packages
npm install --save-dev babel-jest @babel/core @babel/preset-env @babel/preset-typescript ts-jest @types/jest
- To configure babel
Add a new file :babel.config.js Same as package.json Catalog
module.exports = {
presets: [
['@babel/preset-env', {
targets: {
node: 'current'}}],
'@babel/preset-typescript',
],
};
modify tsconfig
- types Type increase jest
"types": [
"node",
"jest"
],
- Compilation exclusion , Test case file , It does not need to be compiled into the project , So in tsconfig in , Compile select exclude
"exclude": [
"node_modules", // exclude node_module
"**/*.test.ts" // Exclude all .test.ts Test case file of the result
]
eslint Error handling
- In general , Use typescript The engineering of , It's usually configured eslint For code checking , Test case file , There may be error prompts , Just eliminate it
ignorePatterns: ['.eslintrc.js', '*.config.js', '*.test.ts'], // Ignored documents
Final configuration parameters
package.json
{
"name": "testforjest",
"version": "1.0.0",
"description": "ts project",
"main": "./dist/main.js",
"scripts": {
"prebuild": "rimraf dist",
"format": "prettier --write \"src/**/*.ts\"",
"lint": "eslint \"src/**/*.ts\"",
"lintfix": "eslint \"src/**/*.ts\" --fix",
"build": "npm run lint &&tsc",
"test": "jest",
"test-c": "jest --coverage",
"formatbuild": "npm run format && npm run build"
},
"keywords": [],
"author": "zdhsoft",
"license": "ts_project",
"devDependencies": {
"@babel/core": "^7.18.6",
"@babel/preset-env": "^7.18.6",
"@babel/preset-typescript": "^7.18.6",
"@types/jest": "^28.1.6",
"@types/lodash": "^4.14.182",
"@types/node": "^16.11.26",
"@typescript-eslint/eslint-plugin": "^5.30.5",
"@typescript-eslint/parser": "^5.30.5",
"babel-jest": "^28.1.3",
"eslint": "^8.19.0",
"eslint-config-google": "^0.14.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-prettier": "^4.2.1",
"jest": "^28.1.3",
"prettier": "^2.7.1",
"prettier-eslint": "^15.0.1",
"ts-jest": "^28.0.7",
"typescript": "^4.7.4"
},
"engines": {
"node": ">=10.0.0",
"npm": ">=6.0.0"
}
}
tsconfig.json
{
“compilerOptions”: {
“module”: “commonjs”,
“declaration”: true,
“removeComments”: true,
“preserveConstEnums”: true,
“lib”: [
“ES2021”
],
“moduleResolution”:“node”,
“emitDecoratorMetadata”: true,
“experimentalDecorators”: true,
“allowSyntheticDefaultImports”: true,
“target”: “ES2021”,
“sourceMap”: true,
“outDir”: “./dist”,
“baseUrl”: “./”,
“incremental”: true,
“skipLibCheck”: true,
“strict”: true,
“strictNullChecks”: true,
“strictFunctionTypes”: true,
“strictPropertyInitialization”: false,
“noImplicitAny”: true,
“suppressImplicitAnyIndexErrors”: true,
“strictBindCallApply”: true,
“forceConsistentCasingInFileNames”: true,
“noImplicitReturns”: true,
“esModuleInterop”: true,
“newLine”:“crlf”,
“typeRoots”: [“@types”],
“types”: [
“node”,
“jest”
],
“noFallthroughCasesInSwitch”: true
},
“include”: [
“src//*.ts"
],
“exclude”: [
“node_modules”,
"/*.test.ts”
]
}
babel.config.js
module.exports = {
presets: [['@babel/preset-env', {
targets: {
node: 'current'}}],
'@babel/preset-typescript',
],
};
jest.config.js
/* * For a detailed explanation regarding each configuration property, visit: * https://jestjs.io/docs/configuration */
module.exports = {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
// bail: 0,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "C:\\Users\\rex\\AppData\\Local\\Temp\\jest",
// Automatically clear mock calls, instances, contexts and results before every test
// clearMocks: false,
// Indicates whether the coverage information should be collected while executing the test
// collectCoverage: false,
// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,
// The directory where Jest should output its coverage files
// coverageDirectory: undefined,
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "\\\\node_modules\\\\"
// ],
// Indicates which provider should be used to instrument code for coverage
coverageProvider: "v8",
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// The default configuration for fake timers
// fakeTimers: {
// "enableGlobally": false
// },
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "mjs",
// "cjs",
// "jsx",
// "ts",
// "tsx",
// "json",
// "node"
// ],
// 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: {},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
// preset: undefined,
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state before every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state and implementation before every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
// testEnvironment: "jest-environment-node",
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "\\\\node_modules\\\\"
// ],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
// This option allows use of a custom test runner
// testRunner: "jest-circus/runner",
// A map from regular expressions to paths to transformers
// transform: undefined,
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "\\\\node_modules\\\\",
// "\\.pnp\\.[^\\\\]+$"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};
.eslintrc.js
module.exports = {
extends: './tsconfig.json',
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
sourceType: 'module',
files: ['*.ts']
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js', '*.config.js', '*.test.ts'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/ban-types': 'off',
'@typescript-eslint/no-non-null-assertion': 'off',
},
};
边栏推荐
- 从ACL 2022 Onsite经历看NLP热点
- Openatom xuprechain open source biweekly report | 2022.7.11-2022.7.22
- 一日千里,追风逐月 | 深势科技发布极致加速版分子对接引擎Uni-Docking
- QT6 with vs Code: compiling source code and basic configuration
- Traffic is not the most important thing for the metauniverse. Whether it can really change the traditional way of life and production is the most important
- 9 best engineering construction project management systems
- 做好项目管理的10个关键点和5大措施
- Argocd user management, RBAC control, script login, APP synchronization
- The idea of the regular crawler of the scratch
- 【terminal】x86 Native Tools Command Prompt for VS 2017
猜你喜欢

Talk about practice, do solid work, and become practical: tour the digitalized land of China

Paper reading: UNET 3+: a full-scale connected UNET for medical image segmentation

File operation-

Leave the factory and sell insurance

CTF Crypto---RSA KCS1_ Oaep mode
![[Yugong series] July 2022 go teaching course 016 logical operators and other operators of operators](/img/36/9ad3f76078153f6af6c5b59d99564a.png)
[Yugong series] July 2022 go teaching course 016 logical operators and other operators of operators

阿里云镜像地址&网易云镜像

华为无线设备配置WAPI-证书安全策略

Vscode saves setting configuration parameters to the difference between users and workspaces

"Wei Lai Cup" 2022 Niuke summer multi school training camp 1 supplementary problem solution (incomplete)
随机推荐
Rambus announces ddr5 memory interface chip portfolio for data centers and PCs
Alibaba cloud image address & Netease cloud image
Shell run command
【每日一题】剑指 Offer II 115. 重建序列
Ask the bosses: MySQL CDC stores configuration data, and Kafka has history
【刷题笔记】搜索插入位置(二分法的活用)
Leave the factory and sell insurance
What are the types of financial products in 2022? Which is suitable for beginners?
Can interface debugging still play like this?
runtimecompiler 和 runtimeonly是什么
华为无线设备配置WPA2-802.1X-AES安全策略
QT6 with vs Code: compiling source code and basic configuration
RPC communication principle and project technology selection
[computer explanation] what should I pay attention to when I go to the computer repair shop to repair the computer?
PADS导出gerber文件
如何在KVM环境中使用网络安装部署多台虚拟服务器
What if Oracle 19C migration encounters large lob tables?
File operation-
集群聊天服务器:项目问题汇总
Wechat applet request requests to carry cookies to verify whether it has logged in