Expect 断言
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
编写测试时,经常需要验证值是否符合特定条件。expect 提供了一系列"匹配器",可帮助您验证不同类型的内容。
更多由 Jest 社区维护的匹配器,请查看 jest-extended。
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
本页中的 TypeScript 示例仅在显式导入 Jest API 的情况下才能按文档所述正常工作:
import {expect, jest, test} from '@jest/globals';
有关如何设置 Jest 与 TypeScript 配合使用的详细信息,请查阅入门指南。
参数详解
- Expect 断言
- 修饰符
- 匹配器
.toBe(value).toHaveBeenCalled().toHaveBeenCalledTimes(number).toHaveBeenCalledWith(arg1, arg2, ...).toHaveBeenLastCalledWith(arg1, arg2, ...).toHaveBeenNthCalledWith(nthCall, arg1, arg2, ....).toHaveReturned().toHaveReturnedTimes(number).toHaveReturnedWith(value).toHaveLastReturnedWith(value).toHaveNthReturnedWith(nthCall, value).toHaveLength(number).toHaveProperty(keyPath, value?).toBeCloseTo(number, numDigits?).toBeDefined().toBeFalsy().toBeGreaterThan(number | bigint).toBeGreaterThanOrEqual(number | bigint).toBeLessThan(number | bigint).toBeLessThanOrEqual(number | bigint).toBeInstanceOf(Class).toBeNull().toBeTruthy().toBeUndefined().toBeNaN().toContain(item).toContainEqual(item).toEqual(value).toMatch(regexp | string).toMatchObject(object).toMatchSnapshot(propertyMatchers?, hint?).toMatchInlineSnapshot(propertyMatchers?, inlineSnapshot).toStrictEqual(value).toThrow(error?).toThrowErrorMatchingSnapshot(hint?).toThrowErrorMatchingInlineSnapshot(inlineSnapshot)
- 非对称匹配器
expect.anything()expect.any(constructor)expect.arrayContaining(array)expect.not.arrayContaining(array)expect.closeTo(number, numDigits?)expect.objectContaining(object)expect.not.objectContaining(object)expect.stringContaining(string)expect.not.stringContaining(string)expect.stringMatching(string | regexp)expect.not.stringMatching(string | regexp)
- 断言计数
- 扩展工具
- id: expect title: Expect 断言
Expect 断言
expect(value)
每次需要测试某个值时都会用到 expect 函数。通常不会单独调用 expect,而是将 expect 与"匹配器"函数配合使用来断言值的特性。
通过示例更容易理解。假设您有个应返回字符串 'grapefruit' 的方法 bestLaCroixFlavor(),测试代码如下:
test('the best flavor is grapefruit', () => {
expect(bestLaCroixFlavor()).toBe('grapefruit');
});
这里的 toBe 就是匹配器函数。下文将介绍多种不同的匹配器函数,用于验证各类情况。
expect 的参数应是代码生成的值,匹配器的参数应是正确值。如果混淆顺序,测试仍能运行,但失败时的错误信息会显得混乱。
修饰符
.not
当您知道如何测试某个条件时,.not 可测试其相反情况。例如测试最佳 La Croix 口味不是椰子味:
test('the best flavor is not coconut', () => {
expect(bestLaCroixFlavor()).not.toBe('coconut');
});
.resolves
使用 resolves 解包已兑现 Promise 的值,以便链式调用其他匹配器。若 Promise 被拒绝,则断言失败。
例如以下代码测试 Promise 是否兑现且结果为 'lemon':
test('resolves to lemon', () => {
// make sure to add a return statement
return expect(Promise.resolve('lemon')).resolves.toBe('lemon');
});
由于仍在测试 Promise,测试本质仍是异步的。因此需要通过返回解包后的断言告知 Jest 等待。
或结合 async/await 使用 .resolves:
test('resolves to lemon', async () => {
await expect(Promise.resolve('lemon')).resolves.toBe('lemon');
await expect(Promise.resolve('lemon')).resolves.not.toBe('octopus');
});
.rejects
使用 .rejects 解包已拒绝 Promise 的原因,以便链式调用其他匹配器。若 Promise 兑现,则断言失败。
例如以下代码测试 Promise 是否因 'octopus' 原因被拒绝:
test('rejects to octopus', () => {
// make sure to add a return statement
return expect(Promise.reject(new Error('octopus'))).rejects.toThrow(
'octopus',
);
});
由于仍在测试 Promise,测试本质仍是异步的。因此需要通过返回解包后的断言告知 Jest 等待。
或结合 async/await 使用 .rejects:
test('rejects to octopus', async () => {
await expect(Promise.reject(new Error('octopus'))).rejects.toThrow('octopus');
});
匹配器
.toBe(value)
使用 .toBe 比较原始值或检查对象实例的引用一致性。它调用 Object.is 进行值比较,比 === 严格相等运算符更适合测试场景。
例如以下代码验证 can 对象的属性:
const can = {
name: 'pamplemousse',
ounces: 12,
};
describe('the can', () => {
test('has 12 ounces', () => {
expect(can.ounces).toBe(12);
});
test('has a sophisticated name', () => {
expect(can.name).toBe('pamplemousse');
});
});
不要用 .toBe 比较浮点数。例如在 JavaScript 中由于舍入误差,0.2 + 0.1 并不严格等于 0.3。处理浮点数时请改用 .toBeCloseTo。
尽管 .toBe 匹配器检查的是引用一致性,但当断言失败时,它会报告值的深度差异对比。如果属性差异无法帮助理解测试失败原因(特别是当报告内容冗长时),可将比较逻辑移至 expect 函数内部。例如,要断言元素是否为相同实例:
-
将
expect(received).toBe(expected)改写为expect(Object.is(received, expected)).toBe(true) -
将
expect(received).not.toBe(expected)改写为expect(Object.is(received, expected)).toBe(false)
.toHaveBeenCalled()
别名:.toBeCalled()
使用 .toHaveBeenCalled 确保模拟函数已被调用。
例如,假设存在 drinkAll(drink, flavour) 函数,该函数接收 drink 方法并 将其应用于所有可用饮料。可通过以下测试用例验证 drink 是否被调用:
function drinkAll(callback, flavour) {
if (flavour !== 'octopus') {
callback(flavour);
}
}
describe('drinkAll', () => {
test('drinks something lemon-flavoured', () => {
const drink = jest.fn();
drinkAll(drink, 'lemon');
expect(drink).toHaveBeenCalled();
});
test('does not drink something octopus-flavoured', () => {
const drink = jest.fn();
drinkAll(drink, 'octopus');
expect(drink).not.toHaveBeenCalled();
});
});