Testing React Apps · Jest 中文文档 | Jest 中文网
tips:在VS code里安装Jest插件,快速开始Debug和查看snapshot
Jest
和 Webpack
一样都有默认配置
npx jest --init
:初始化默认配置。
在运行命令行的时候,会弹出一些选项,比如:
typescript
覆盖率报告
node 环境
或者浏览器环境
清除工作
其会生成**jest.config.js
**
import React from "react";
import renderer from "react-test-renderer";
function add(a, b) {
return a + b;
}
function minus(a, b) {
return a - b;
}
function multi(a, b) {
return a * b;
}
test("测试加法 3 + 3", () => {
expect(add(3, 3)).toBe(6);
});
test("测试减法 3 - 3", () => {
expect(minus(3, 3)).toBe(0);
});
test("测试乘法 3 * 3", () => {
expect(multi(3, 3)).toBe(10); // 错误的结果
});
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NtPWdORr-1655021483616)(https://s3-us-west-2.amazonaws.com/secure.notion-static.com/a06aa2fb-dd5a-4b9d-9a32-d4c0170ee811/Untitled.png)]
toBe
:测试两个对象的值是否相等,类似于 js 中的 === 运算符toEqual
:测试两个对象的原始值是否相等,只检查内容,不检查引用toBeNull
:测试对象的值是否为null,效果相当于**.toBe(null)
**toBeUndefined
:测试对象的值是否为undefined,效果相当于**.toBe(undefined)
**toBeDefined
:测试值是否被定义过,除了undefined
之外都会通过测试toBeTruthy
:检查值转成布尔值之后是否为真值toBeFalsy
:检查值转成布尔值之后是否为假值not
:取反匹配器,相当于 js 中的 ! 运算符(搭配其他匹配器使用)toBeGreaterThan
:检查接收值是否大于期待值toBeLessThan
:检查接收值是否小于期待值toBeGreaterThanOrEqual
:检查接收值是否大于等于期待值toBeLessThanOrEqual
:检查接收值是否小于等于期待值toBeCloseTo
:检查浮点数是否接近(是否近似相等)toContain
:检查数组中是否包含某一项(类似于 js 中的 includes 方法)toThrow
:测试函数在调用时是否有异常抛出test("测试返回值为 { success: true }", () => {
return expect(new Promise((rs)=>{return rs({ success: true })}))
.resolves.toEqual(
{
success: true
}
);
});
与之匹配的是**.rejects
**
test("测试返回成功", async () => {
await expect(new Promise((rs)=>{return rs({ success: true })})).resolves.toEqual({ success: true });
});
test("测试返回失败", async () => {
await expect(new Promise((rs,rj)=>{return rj("404")})).rejects.toMatch("404");
});
let counter = null;
//让每次进行测试的时候重新new一个class以避免各个测试样例间的干扰
beforeEach(() => {
counter = new Counter();
});
test("测试 counter 的 add 方法", () => {
expect(counter.number).toBe(0);
counter.add();
expect(counter.number).toBe(1);
});
test("测试 counter 的 minus 方法", () => {
expect(counter.number).toBe(0);
counter.minus();
expect(counter.number).toBe(-1);
});
其他的
beforeAll
:在所有测试用例执行之前调用(调用一次)afterAll
:在所有测试用例执行之后调用(调用一次)beforeEach
:在每个测试用例执行之前调用(调用多次)afterEach
:在每个测试用例执行之后调用(调用多次)describe("测试分组1", () => {
beforeAll(() => {
console.log("测试分组1 - beforeAll");
});
afterAll(() => {
console.log("测试分组1 - afterAll");
});
test("测试", () => {
console.log("测试分组1 测试");
expect(1 + 1).toBe(2);
});
});
describe("测试分组2", () => {
beforeAll(() => {
console.log("测试分组2 - beforeAll");
});
afterAll(() => {
console.log("测试分组2 - afterAll");
});
test("测试", () => {
console.log("测试分组2 测试");
expect(1 + 1).toBe(2);
});
});
//可多层嵌套
describe
都可以有自己的钩子函数
describe
都有自己的作用域
describe
里面的钩子函数
只对自己作用域
下面所有的测试用例
都生效describe
是多层嵌套的,那么测试用例执行的顺序是由外到内