当前位置:网站首页>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',
},
};
边栏推荐
- BOM overview
- 9 best engineering construction project management systems
- %d,%s,%c,%x
- New functions of shixizhi are online. These new functions are online in June. Can you use them?
- 论文阅读:UNET 3+: A FULL-SCALE CONNECTED UNET FOR MEDICAL IMAGE SEGMENTATION
- List derivation
- Electronic Association C language level 2 60, integer parity sort (real question in June 2021)
- Octopus network community call 1 starts Octopus Dao construction
- LeetCode118. 杨辉三角
- Baidu Post Bar crawler gets web pages
猜你喜欢

9 best engineering construction project management systems

Security compliance, non-stop discounts! High quality travel service, "enjoy the road" for you

NLP hotspots from ACL 2022 onsite experience

vulnhub CyberSploit: 1

vulnhub CyberSploit: 1

Wechat applet switchtab transmit parameters and receive parameters

error: redefinition of

leetcode刷题:动态规划06(整数拆分)

2022天工杯CTF---crypto1 wp

Openatom xuprechain open source biweekly report | 2022.7.11-2022.7.22
随机推荐
[knowledge summary] block and value range block
一日千里,追风逐月 | 深势科技发布极致加速版分子对接引擎Uni-Docking
分布式爬虫中的增量爬虫
Lidar construction map (overlay grid construction map)
北京内推 | 微软STCA招聘NLP/IR/DL方向研究型实习生(可远程)
vulnhub CyberSploit: 1
Lpad() function and (row_number() over (order by) +...)
When importing data in batches, you always prompt "failure reason: SQL parsing failure: parsing file failure:: null". What's the matter?
New tea, start "fighting in groups"
The income of bank financial management is getting lower and lower. Now which financial products have high income?
First, how about qifujin
CTF Crypto---RSA KCS1_ Oaep mode
CTF Crypto---RSA KCS1_OAEP模式
[semidrive source code analysis] [drive bringup] 38 - norflash & EMMC partition configuration
Luo min's backwater battle in qudian
Incremental crawler in distributed crawler
Leetcode 206. reverse linked list I
数据提交类型 Request Payload 与 Form Data 的区别总结
Day by day, month by month | Shenzhen potential technology released the extreme accelerated version of molecular docking engine uni docking
2022天工杯CTF---crypto1 wp