更新时间:2021-09-03 一个么的感情的 api 学习机器。。。如果你也在学测试,来保证自己的 javascript 代码的正确性。。。
Jest 配置文件解读
- 命令行 + 脚本的运行模式,其实开始,并不需要这么多 api,反而开始的时候,这些配置成了学习的负担。
配置文件定义位置
- 项目根目录
jest.config.(j/t)s
package.json
的jest
文件npm scripts
的jest --config path/path1
自定以配置文件位置
1. 自动 mock:automock
针对 module,module 中的 api 不会有 jest 中需要的,通过此配置可以告诉 jest,自动添加 api。
- 类型: boolean
- 默认值:false
// jest.config.js
module.exports = {
automock: false,
}
2. 错误后停止的处理🤚:bail
- 类型:number
- 默认值:0
// jest.config.js
module.exports = {
bail: 0, // 有测试错误后就停止错误
}
3. jest 会缓存依赖等一些信息:cacheDirectory
- 类型:string
- 默认值:/tmp/<path>
// jest.config.js
module.exports = {
cacheDirctory: `/temp/<path>`
}
4.每次测试之前自动清除模拟调用和实例: clearMocks
- 类型:boolean
- 默认值:false
// jest.config.js
module.exports = {
clearMocks: false
}
5. 是否应该收集测试覆盖率:collectCoverage
- 类型:boolean
- 默认值:false
// jest.config.js
module.exports = {
collectCoverage: false
}
6. 从哪里收集测试覆盖率:collectCoverageFrom
- 类型:undefined || string[]
- 默认值:undefined
- 基础: 建立在 rootDir,也会排出 node_modules 等其他不相关目录。
// jest.config.js
module.exports = {
collectCoverageFrom: undefined
};
module.exports = {
collectCoverageFrom: [
"**/*.{js,jsx, tsx, ts}" , // 所有 js/ts/jsx/tsx
]
}
7. Jest 输出覆盖的目录:coverageDirectory
- 类型:undefined || string
- 默认值:undefined
// jest.config.js
module.exports = {
collectCoverageFrom: undefined
};
8. 正则匹配忽略收集路径:coveragePathIgnorePatterns
- 类型:undefined || string
- 默认值:undefined
// jest.config.js
module.exports = {
coveragePathIgnorePatterns: [
"/node_modules/", // 这个目录的内容是不用 jest 处理的
]
};
9. 指定哪种程序确定代码覆盖率:coverageProvider
- 类型:string
- 默认值:'v8'
// jest.config.js
module.exports = {
coverageProvider: 'v8' || 'babel',
};
10. jest 指定覆盖率报告者:coverageReporters
- 类型:string
- 默认值:["json", "lcov", "text", "clover"]
- 所有 istanbul reporter 都是能用的
// jest.config.js
module.exports = {
coverageReporters: ["json", "text", "lcov", "clover"],
};
11. 覆盖率最小阀值:coverageThreshold
- 类型:undefined ||
[object]
- 默认值:["json", "lcov", "text", "clover"]
// jest.config.js
module.exports = {
coverageThreshold: undefined,
};
12. 自定义依赖提取路径:dependencyExtractor
- 类型:undefined ||
[object]
- 默认值:undefined
// jest.config.js
module.exports = {
dependencyExtractor: undefined,
};
13. 给测试打上标签:displayName
- 类型:undefiend | string | object
- 默认值:undefined
// jest.config.js
module.exports = {
displayName: {name: 'CLIENT',color: 'blue'} || 'string',
};
主要用于多项目
14. 抛出有用的错误:errorOnDeprecated
- 类型:boolean
- 默认值:false
// jest.config.js
module.exports = {
errorOnDeprecated: false,
};
15. 扩展 esm modules
: extensionsToTreatAsEsm
- 类型
- 默认值:
// jest.config.js
module.exports = {
extensionsToTreatAsEsm: [".mjs", ".ts"]
}
16. nodejs vm 支持:extraGlobal
- 类型:undefined || any[]
- 默认值: undefined
该
vm
模块支持在 V8 虚拟机上下文中编译和运行代码
// jest.config.js
module.exports = {
"extraGlobal": ["Math"]
}
17. 收集被忽略的代码覆盖率: forceCoverageMatch
- 类型:string[]
- 默认值:数组
// jest.config.js
module.exports = {
forceCoverageMatch: [],
}
18. 测试环境中可使用的全局变量:globals
- 类型: object
- 默认值:空对象
// jest.config.js
module.exports = {
globals: {},
}
19. 异步模块导出路径(之前):globalSetup
- 类型: undefined || string[]
- 默认值:undefined
// jest.config.js
module.exports = {
globalSetup: undefined,
}
20. 异步模块导出路径(之后):globalTeardown
- 类型: undefined || string[]
- 默认值:undefined
// jest.config.js
module.exports = {
globalTeardown: undefined,
}
21. jest-haste-map 的相关配置: haste
haste 基本上用户上,所有官方提供了类型:jestjs.io/docs/config…
22. 注入全局api: injectGlobals
- 类型: boolean
- 默认值:true
在 jest 中能直接使用,jest api,而不用显示的导入,就是这个 API 在其作用。如果没有设置为 true, 需要在 @jest/globals
导入。
// jest.config.js
module.exports = {
injectGlobals: true,
}
const {expect, jest, test} = require('@jest/globals')
23. 最的并发数:maxConcurrency
- 类型: number
- 默认值:5
// jest.config.js
module.exports = {
maxConcurrency: 5,
}
24. 最大现线程数:maxWorkers
- 类型:string | number
- 默认值: unknows
// jest.config.js
module.exports = {
maxWorkers: '50%'
}
25. 模块文件目录 moduleDirectories
- 类型:string[]
- 默认值:node_modules
// jest.config.js
module.exports = {
moduleDirectories: ["node_modules"]
}
26. 模块文件扩展:moduleFileExtensions
- 类型:string[]
- 默认值:
["js", "jsx", "ts", "tsx", "json", "node"]
// jest.config.js
module.exports = {
moduleDirectories: ["node_modules"]
}
27. 模块名映射:moduleNameMapper
- 类型:object
- 默认值:null
// jest.config.js
module.exports = {
moduleDirectories: ["node_modules"]
}
28. 模块路径匹配规则:modulePathIgnorePatterns
- 类型:
string[]
- 默认值:
[]
// jest.config.js
module.exports = {
modulePathIgnorePatterns: []
}
29. 模块路径:modulePaths
- 类型:
string[]
- 默认值:
[]
// jest.config.js
module.exports = {
modulePathIgnorePatterns: []
}
30. 测试结果通知:notify
- 类型:
boolean
- 默认值:false
// jest.config.js
module.exports = {
notify: false
}
31. notifyMode
- 类型:
failure-change
|always
|failure
|success
|change
|success-change
|failure-change
- 默认值:false
// jest.config.js
module.exports = {
notifyMode: 'failure-change'
}
32. preset
- 类型:
string | undefined
- 默认值:
undefined
// jest.config.js
module.exports = {
"preset": "foo-bar"
}
33. prettier路径:prettierPath
- 类型:
string | undefined
- 默认值:
undefined
用于 snapshots
// jest.config.js
module.exports = {
prettierPath: 'prettier'
}
34. 指定jest测试路径:project
- 类型:
undefined | any[]
- 默认值:
undefined
// jest.config.js
module.exports = {
projects: [`<rootDir>`, '<rootDir>/example']
}
35. 自定义:reporters
- 类型:
undefined | moduleName[] | [moduleName, options][]
- 默认值: undefined
// jest.config.js
module.exports = {
"reporters": ["default", "<rootDir>/my-custom-reporter.js"]
}
36. 重置mocks:resetMocks
在每一个测试之前自动重置 mocks:
- 类型: boolean
- 默认值: false
// jest.config.js
module.exports = {
resetMocks: false
}
37. 重置模块:resetModules
- 类型: boolean
- 默认值:false
// jest.config.js
module.exports = {
resetModules: false,
}
38. resolver
自定义 resolver 的路径:
- 类型: string
- 默认值:undefined
// jest.config.js
module.exports = {
resolver: undefined
}
39. restoreMocks
自动的恢复到回复模拟状态:
- 类型: boolean
- 默认值:false
// jest.config.js
module.exports = {
restoreMocks: false,
}
40. rootDir
测试根目录:
- 类型:string
- 默认值:包含了 jest 配置文件的根目录
// jest.config.js
module.exports = {
rootDir: 'src'
}
41. roots
Jest 的检索文件的根目录:
- 类型:
string[]
- 默认值:
["<rootDir>"]
// jest.config.js
module.exports = {
roots: ["<rootDir>"]
}
42. 运行器:runner
- 类型:
- jest-runner-eslint
- jest-runner-mocha
- jest-runner-tsc
- jest-runner-prettier
- jest-runner
- 默认值:jest-runner
// jest.config.js
module.exports = {
runner: "jest-runner"
}
43. setupFiles
每次测试之前运行一些代码配置,或者环境变量:
- 类型:
string[]
- 默认值:
[]
// jest.config.js
module.exports = {
setupFiles: []
}
44. setupFilesAfterEnv
每次测试之后运行运行代码,或者环境变量
- 类型:
string[]
- 默认值:
[]
// jest.config.js
module.exports = {
setupFilesAfterEnv: []
}
45. slowTestThreshold
慢测试报告次数:
- 类型: number
- 默认值: 5
// jest.config.js
module.exports = {
slowTestThreshold: []
}
46. snapshot 格式化:snapshotFormat
// jest.config.js
module.exports = {
"snapshotFormat": {
"printBasicPrototype": false
}
}
47. snapshot 解析器:snapshotResolver
- 类型
- 默认值
const resolver = require('./resolver.js')
// jest.config.js
module.exports = {
snapshotResolver: {
snapshotResolver: undefined | pathString
}
}
// resolver.js 官方例子
module.exports = {
// resolves from test to snapshot path
resolveSnapshotPath: (testPath, snapshotExtension) =>
testPath.replace('__tests__', '__snapshots__') + snapshotExtension,
// resolves from snapshot to test path
resolveTestPath: (snapshotFilePath, snapshotExtension) =>
snapshotFilePath
.replace('__snapshots__', '__tests__')
.slice(0, -snapshotExtension.length),
// Example test path, used for preflight consistency check of the implementation above
testPathForConsistencyCheck: 'some/__tests__/example.test.js',
};
48. snapshot 序列化:snapshotSerializers
- 类型:
Array[stringPath]
- 默认值:
[]
// jest.config.js
module.exports = {
"snapshotSerializers": [],
}
49. testEnvironment
测试环境: node/jsdom,可以使用 js 的注释语法指定 @jest 的测试环境
- 类型: string
- 默认值; node
// jest.config.js
module.exports = {
"testEnvironment": "node",
}
50. 测试环境配置项目:testEnvironmentOptions
- 类型: Object
- 默认值: {}
// jest.config.js
module.exports = {
testEnvironmentOptions: {}
}
51. 测试失败次数 n 退出: testFailureExitCode
- 类型: number
- 默认值: 1
// jest.config.js
module.exports = {
testFailureExitCode: 1,
}
52. 测试匹配:testMatch
- 类型:
any[]
- 默认值:
[ "**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)" ]
// jest.config.js
module.exports = {
testMatch: [ "**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)" ]
}
53. testPathIgnorePatterns
测试路径匹配模式:
- 类型:
any[]
- 默认值:
["/node_modules/"]
// jest.config.js
module.exports = {
testPathIgnorePatterns: ["/node_modules/"]
}
54. 正则匹配测试: testRegex
- 类型:
string | string[]
- 默认值:
(/__tests__/.*|(\\.|/)(test|spec))\\.[jt]sx?$
// jest.config.js
module.exports = {
testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.[jt]sx?$"
}
55. 自定义测试结果处理器:testResultsProcessor
- 类型:
string[]
- 默认值:
undefined
// jest.config.js
module.exports = {
testResultsProcessor: undefined
}
56. 自定义测试运行器:testRunner
- 类型:
string
- 默认值: jest-cirus/runner`
// jest.config.js
module.exports = {
testRunner: "jest-cirus/runner"
}
57. testSequencer
- 类型:
string[]
- 默认值:
@jest/test-sequencer
// jest.config.hs
module.exports = {
testSequencer: '@jest/test-sequencer'
}
58. 测试超时:testTimeout
- 类型: number
- 默认值:5000
// jest.config.js
module.exports = {
testTimeout: 5000, // ms
}
59. testURL
jsdom 环境测试地址, 反应在 location.herf 属性上。
- 类型:string
- 默认值:
http://localhost
// jest.config.js
module.exports = {
testURL: `http://localhost`,
}
60. timers
- 类型:
string
- 默认值:
real
// jest.config.js
module.exports = {
timers: 'real'
}
61. 转换器: transform
- 类型:
Object
- 默认值:
{"\\.[jt]sx?$": "babel-jest"}
// jest.config.js
module.exports = {
transform: {
"\\.[jt]sx?$": "babel-jest"
}
}
编译器的种类:
- babel
- typescript
- 自己的被编译器
62. transformIgnorePatterns
- 类型:
string[]
- 默认值:
["/node_modules/", "\\.pnp\\.[^\\\/]+$"]
转换器要忽略的路径(使用正则匹配):
// jest.config.js
module.exports = {
transformIgnorePatterns: ["/node_modules/", "\\.pnp\\.[^\\\/]+$"]
}
63. unmockedModulePathPatterns
- 类型:array
- 默认值:
[]
非 mock module
路径匹配:
// jest.config.js
module.exports = {
unmockedModulePathPatterns: []
}
64. verbose
- 类型: boolean
- 默认值: false
指示是否应在运行期间报告每个测试:
// jest.config.js
module.exports = {
verbose: false,
}
65. watchPathIgnorePatterns
- 类型:
string[]
- 默认值:
[]
在监视模式下重新运行测试之前,与所有源文件路径匹配的RegExp模式数组:
// jest.config.js
module.exports = {
watchPathIgorePatterns: []
}
66. watchPlugins
- 类型:
string[]
- 默认值:
any[]
// jest.config.js
module.exports = {
wathchPlugins: []
}
- jest-watch-master
- jest-watch-select-projects
- jest-watch-suspend
- jest-watch-typeahead
- jest-watch-yarn-workspace
67. watchman
// jest.config.js
module.exports = {
watchman: true,
}
68. //
评论内容
// jest.config.js
module.exports = {
"jest": {
"//": "your jest test",
}
}
这里主要是学习 Jest 的配置文件,相对的相对 Jest 有一个比较完整的认识。 umijs 中主要就是用到了 Jest。
Jest 全局 api
测试套件 Test Suite
通常把一组相关的测试称为一个测试套件。
Jest 中如果,一个测试文件没有使用 describe 来包裹,则是一个默认的测试套件。测试套件可以通过全局 API, describe 来进行包裹,并且 describe 是支持嵌套的。
Jest describe 函数上扩展了新的属性:
- describe
- describe.each
- describe.only?.each
- describe.skip?.only
测试用例
测试用例(Test Case)是指对一项特定的软件产品进行测试任务的描述,体现测试方案、方法、技术和策略。
- test/it (it 是测试别名,在其他的测试框架中使用 it 比较多)
- test.concurrent(?.(only/skip)?.each)
- test.each
- test.only
- test.skip?.each
- test.todo
套件前置/后置api(或者 hooks)
// xxx.test.js
afterAll(() => {
globalFn()
})
beforeAll(() => {
globalBefore()
})
测试用例前置/后置 api(或者 hooks)
// xxx.test.js
afterEach(() => {
eachFn();
})
beforeEach(() => {
beforeFn();
})