Jest断言与匹配器
大约 2 分钟
Jest 断言与匹配器(Expect)
推荐文档:https://blog.csdn.net/biraotian/article/details/111329794
常用匹配器
/* expect断言测试 */
const errorFn = () => {
throw new Error("错误信息!!");
};
describe("Expect断言测试", () => {
/* 常用 */
it("toBe():全等判断", () => {
expect(1).toBe(1);
});
it("not toBe:不等于", () => {
expect(2).not.toBe(1);
});
it("toEqual:匹配对象是否相等", () => {
expect({ username: "sunshine" }).toEqual({ username: "sunshine" });
});
it("toBeNull:匹配值是否为null", () => {
expect(null).toBeNull();
});
it("toBeUndefined:匹配是否为undefined", () => {
expect(undefined).toBeUndefined();
});
it("toBeTruthy:匹配某个值等于true", () => {
expect(true).toBeTruthy();
});
it("toBeFalsy:匹配某个值为假", () => {
expect(false).toBeFalsy();
});
/* 数字相关对比 */
it("toBeGreaterThan:比某个数字大", () => {
expect(1).toBeGreaterThan(0);
});
it("toBeLessThan:比某个数字小", () => {
expect(2).toBeLessThan(3);
});
it("toBeGreaterThanOrEqual:大于或等于某个数字", () => {
expect(2).toBeGreaterThanOrEqual(2);
});
it("toBeLessThanOrEqual:小于或等于某个数字", () => {
expect(1).toBeLessThanOrEqual(1);
});
it("toBeCloseTo:计算浮点数字相加是否相等", () => {
// expect(0.1 + 0.2).toBe(0.3); // js中0.1 + 0.2 = 0.30000000000000004
expect(0.1 + 0.2).toBeCloseTo(0.3);
});
/* 字符串相关 */
it("toMatch:字符串内是否包含某个字符串", () => {
expect("hello").toMatch("hel");
});
/* 数组相关 */
it("toContain:是否包含该元素", () => {
expect([1, 2, 3, 4]).toContain(3);
expect(new Set([1, 2, 3, 4])).toContain(3);
});
/* 异常相关 */
it("抛出错误", () => {
expect(errorFn).toThrow();
});
});
补充匹配器
describe("补充匹配器", () => {
it("toMatch:正则匹配字符串", () => {
expect("hello world").toMatch(/world$/);
});
it("toHaveLength:断言数组/字符串长度", () => {
expect([1, 2, 3]).toHaveLength(3);
expect("abc").toHaveLength(3);
});
it("toThrow:断言错误信息内容", () => {
const fn = () => {
throw new Error("参数错误");
};
expect(fn).toThrow("参数错误");
});
it("toContainEqual:断言对象数组中是否包含某个对象", () => {
expect([{ id: 1 }, { id: 2 }]).toContainEqual({ id: 2 });
});
it("toMatchSnapshot:快照匹配,结构不变即通过", () => {
const user = { name: "sunshine", role: "admin" };
expect(user).toMatchSnapshot();
});
});
异步代码断言
// 方法一:回调函数,手动调用 done 表示测试结束,注意调用 done(error) 处理异常分支
it("回调式异步", done => {
fetchData((err, data) => {
if (err) return done(err);
expect(data).toBe("ok");
done();
});
});
// 方法二:返回 Promise
it("Promise式异步", () => {
return fetchData().then(data => {
expect(data).toBe("ok");
});
});
// 方法三:async/await(推荐)
it("async/await式异步", async () => {
const data = await fetchData();
expect(data).toBe("ok");
});
// 方法四:resolves / rejects 匹配器
it("resolves匹配器", async () => {
await expect(fetchData()).resolves.toBe("ok");
});
it("rejects匹配器", async () => {
await expect(fetchError()).rejects.toThrow("失败");
});
Loading...
