Vue3 + ts + jest 单元测试 配置以及使用
安装 Jest
全局:npm install -g jest 或局部: npm install -D jest
在 package.json 中指定 test 脚本:
Jest 的测试脚本名形如 .test.js ,不论 Jest 是全局运行还是通过 npm test 运行, 它都会执行当前目录下所有的 .test.js 或 .spec.js 文件、完成测试。
"scripts": {
"test": "jest"}
总体概念
1.jest单元测试的写法为三步,引入测试内容,运行测试内容,最后进行比较,是否达到预期。 Jest中的断言使用expect, 它接受一个参数,就是运行测试内容的结果,返回一个对象,这个对象来调用匹配器(toBe/。。。)
补充:匹配器:
toBe():绝对相等(===) toEqual():简单类型绝对匹配;复杂类型内容结果的匹配 toBeNull():匹配null toBeUndefined():匹配undefined toBeDefined():匹配非undefined toBeTruthy():匹配转化后为true toBeFalsy():匹配转化后为false toBeGreaterThan():相当于大于号 toBeLessThan():相当于小于号 toBeGreaterThanOrEqual():相当于大于等于号 toBeLessThanOrEqual():相当于大于等于号 toBeCloseTo():解决js浮点错误 toMatch(regExp/string):用正则表达式或者字符串匹配字符串片段 toContain():匹配数组或者Set中的某一项 toThrow():匹配异常处理,如果抛出了异常就过测试用例
配置
tsconfig.json中配置
"compilerOptions":{
"outDir": "./outDir",
}
.eslintignore中配置
/build/* /dist/* /node_modules/* src/public/* /outDir/*
.eslintrc.js 中配置
eslint 报错 expect is not defined…
"env": {
"jest": true, // 关键在这
"browser": true,
"es6": true,
"es7": true,
"node": true,
}
文件路径:
demo测试
src/demo.js
function sum(a, b) {
return a + b;
}
function sort(arr = []) {
`在这里插入代码片`
return arr.sort()
}
module.exports = {
sum,
sort,
}
test/demo.test.js
const {
sum,
sort
} = require(../demo.js)
test(测试sum方法:10 + 10 = 30 , () => {
expect(sum(10, 10)).toBe(30);
})
describe(测试 sort 方法功能, () => {
it(正常测试, () => {
const data = sort([1, 3, 5, 2, 4]);
expect(data).toEqual([1, 2, 3, 4, 5]);
})
it(不传值, () => {
const data = sort();
expect(data).toEqual([]);
})
})
运行yarn test成功如下:
$ jest
PASS test/demo.test.js
√ 测试sum方法:10 + 20 = 30 (2 ms)
测试 sort 方法功能
√ 正常测试 (1 ms)
√ 不传值 (1 ms)
Test Suites: 1 passed, 1 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: 1.349 s
Ran all test suites.
Done in 2.88s.
PS C:UserswynDesktopvtest> yarn test
yarn run v1.22.19
$ jest
FAIL test/demo.test.js
× 测试sum方法:10 + 10 = 30 (3 ms)
测试 sort 方法功能
√ 正常测试 (1 ms)
√ 不传值 (1 ms)
● 测试sum方法:10 + 10 = 30
expect(received).toBe(expected) // Object.is equality
Expected: 30
Received: 20
5 |
6 | test(测试sum方法:10 + 10 = 30 , () => {
> 7 | expect(sum(10, 10)).toBe(30);
| ^
8 | })
9 |
10 | describe(测试 sort 方法功能, () => {
at Object.toBe (test/demo.test.js:7:22)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 2 passed, 3 total
Snapshots: 0 total
Time: 1.155 s, estimated 2 s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
下一篇:
JVM内存模型篇【JVM内存模型】
