使用匹配器
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
Jest 使用"匹配器"让你以不同方式验证值。本文档将介绍一些常用匹配器。完整列表请查阅 expect API 文档。
常用匹配器
最简单的测试方法是精确相等验证。
test('two plus two is four', () => {
expect(2 + 2).toBe(4);
});
在这段代码中,expect(2 + 2) 返回一个"期望值对象"。通常你不会直接操作这个对象,而是在它上面调用匹配器方法。这里 .toBe(4) 就是匹配器。Jest 运行时将跟踪所有失败的匹配器,以便为你输出清晰的错误信息。
toBe 使用 Object.is 检测精确相等。如需验证对象值,请使用 toEqual:
test('object assignment', () => {
const data = {one: 1};
data['two'] = 2;
expect(data).toEqual({one: 1, two: 2});
});
toEqual 会递归检查对象或数组的每个字段。
toEqual 会忽略包含 undefined 属性的对象键、undefined 数组元素、数组空位或对象类型差异。如需考虑这些情况,请改用 toStrictEqual。
你还可以使用 not 测试匹配器的相反情况:
test('adding positive numbers is not zero', () => {
for (let a = 1; a < 10; a++) {
for (let b = 1; b < 10; b++) {
expect(a + b).not.toBe(0);
}
}
});
真值判断
测试中有时需要区分 undefined、null 和 false,但有时又希望一视同仁。Jest 提供了辅助方法让你明确表达验证意图。
-
toBeNull仅匹配null -
toBeUndefined仅匹配undefined -
toBeDefined是toBeUndefined的反义 -
toBeTruthy匹配所有被if语句视为 true 的值 -
toBeFalsy匹配所有被if语句视为 false 的值
例如:
test('null', () => {
const n = null;
expect(n).toBeNull();
expect(n).toBeDefined();
expect(n).not.toBeUndefined();
expect(n).not.toBeTruthy();
expect(n).toBeFalsy();
});
test('zero', () => {
const z = 0;
expect(z).not.toBeNull();
expect(z).toBeDefined();
expect(z).not.toBeUndefined();
expect(z).not.toBeTruthy();
expect(z).toBeFalsy();
});
应选用最能精确表达代码意图的匹配器。
数字验证
多数数字比较方法都有对应的匹配器。
test('two plus two', () => {
const value = 2 + 2;
expect(value).toBeGreaterThan(3);
expect(value).toBeGreaterThanOrEqual(3.5);
expect(value).toBeLessThan(5);
expect(value).toBeLessThanOrEqual(4.5);
// toBe and toEqual are equivalent for numbers
expect(value).toBe(4);
expect(value).toEqual(4);
});
验证浮点数相等时,请使用 toBeCloseTo 而非 toEqual,避免因细微舍入误差导致测试失败。
test('adding floating point numbers', () => {
const value = 0.1 + 0.2;
//expect(value).toBe(0.3); This won't work because of rounding error
expect(value).toBeCloseTo(0.3); // This works.
});
字符串验证
可使用 toMatch 通过正则表达式检查字符串:
test('there is no I in team', () => {
expect('team').not.toMatch(/I/);
});
test('but there is a "stop" in Christoph', () => {
expect('Christoph').toMatch(/stop/);
});
数组与可迭代对象
使用 toContain 检查数组或可迭代对象是否包含特定元素:
const shoppingList = [
'diapers',
'kleenex',
'trash bags',
'paper towels',
'milk',
];
test('the shopping list has milk on it', () => {
expect(shoppingList).toContain('milk');
expect(new Set(shoppingList)).toContain('milk');
});
异常处理
如需测试函数 调用时是否抛出错误,请使用 toThrow。
function compileAndroidCode() {
throw new Error('you are using the wrong JDK!');
}
test('compiling android goes as expected', () => {
expect(() => compileAndroidCode()).toThrow();
expect(() => compileAndroidCode()).toThrow(Error);
// You can also use a string that must be contained in the error message or a regexp
expect(() => compileAndroidCode()).toThrow('you are using the wrong JDK');
expect(() => compileAndroidCode()).toThrow(/JDK/);
// Or you can match an exact error message using a regexp like below
expect(() => compileAndroidCode()).toThrow(/^you are using the wrong JDK$/); // Test fails
expect(() => compileAndroidCode()).toThrow(/^you are using the wrong JDK!$/); // Test pass
});
抛出异常的函数必须在包装函数内调用,否则 toThrow 断言会失败。
更多功能
以上仅是部分示例。完整匹配器列表请查阅参考文档。
了解可用匹配器后,下一步可学习 Jest 如何支持异步代码测试。