使用匹配器
Jest 使用 "matchers" 让你以不同的方式测试值。本文档将介绍一些常用的匹配器。有关完整列表,请参阅 expect
API 文档。
¥Jest uses "matchers" to let you test values in different ways. This document will introduce some commonly used matchers. For the full list, see the expect
API doc.
常见匹配器
¥Common Matchers
测试值的最简单方法是完全相等。
¥The simplest way to test a value is with exact equality.
test('two plus two is four', () => {
expect(2 + 2).toBe(4);
});
在此代码中,expect(2 + 2)
返回一个 "expectation" 对象。除了调用匹配器之外,你通常不会对这些期望对象做太多事情。在此代码中,.toBe(4)
是匹配器。当 Jest 运行时,它会跟踪所有失败的匹配器,以便它可以为你打印出不错的错误消息。
¥In this code, expect(2 + 2)
returns an "expectation" object. You typically won't do much with these expectation objects except call matchers on them. In this code, .toBe(4)
is the matcher. When Jest runs, it tracks all the failing matchers so that it can print out nice error messages for you.
toBe
使用 Object.is
来测试完全相等。如果要检查对象的值,请使用 toEqual
:
¥toBe
uses Object.is
to test exact equality. If you want to check the value of an object, use toEqual
:
test('object assignment', () => {
const data = {one: 1};
data['two'] = 2;
expect(data).toEqual({one: 1, two: 2});
});
toEqual
递归地检查对象或数组的每个字段。
¥toEqual
recursively checks every field of an object or array.
toEqual
忽略具有 undefined
属性、undefined
数组项、数组稀疏性或对象类型不匹配的对象键。要考虑这些,请改用 toStrictEqual
。
¥toEqual
ignores object keys with undefined
properties, undefined
array items, array sparseness, or object type mismatch. To take these into account use toStrictEqual
instead.
你还可以使用 not
测试匹配器的反面:
¥You can also test for the opposite of a matcher using 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);
}
}
});
真实性
¥Truthiness
在测试中,有时需要区分 undefined
、null
和 false
,但有时又不想区别对待。Jest 包含辅助程序,可让你明确表达自己想要的内容。
¥In tests, you sometimes need to distinguish between undefined
, null
, and false
, but you sometimes do not want to treat these differently. Jest contains helpers that let you be explicit about what you want.
-
toBeNull
仅匹配null
¥
toBeNull
matches onlynull
-
toBeUndefined
仅匹配undefined
¥
toBeUndefined
matches onlyundefined
-
toBeDefined
与toBeUndefined
相反¥
toBeDefined
is the opposite oftoBeUndefined
-
toBeTruthy
匹配if
语句视为 true 的任何内容¥
toBeTruthy
matches anything that anif
statement treats as true -
toBeFalsy
匹配if
语句视为 false 的任何内容¥
toBeFalsy
matches anything that anif
statement treats as false
例如:
¥For example:
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();
});
你应该使用与你希望代码执行的操作最精确对应的匹配器。
¥You should use the matcher that most precisely corresponds to what you want your code to be doing.
数字
¥Numbers
大多数比较数字的方法都有匹配器等价物。
¥Most ways of comparing numbers have matcher equivalents.
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
,因为你不希望测试依赖于微小的舍入误差。
¥For floating point equality, use toBeCloseTo
instead of toEqual
, because you don't want a test to depend on a tiny rounding error.
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.
});
字符串
¥Strings
你可以使用 toMatch
根据正则表达式检查字符串:
¥You can check strings against regular expressions with 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/);
});
数组和可迭代对象
¥Arrays and iterables
你可以使用 toContain
检查数组或可迭代是否包含特定项目:
¥You can check if an array or iterable contains a particular item using 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');
});
例外情况
¥Exceptions
如果要测试某个特定函数在调用时是否抛出错误,请使用 toThrow
。
¥If you want to test whether a particular function throws an error when it's called, use 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
断言将失败。
¥The function that throws an exception needs to be invoked within a wrapping function otherwise the toThrow
assertion will fail.
以及更多
¥And More
这只是一个味道。有关匹配器的完整列表,请查看 参考文档。
¥This is just a taste. For a complete list of matchers, check out the reference docs.
一旦你了解了可用的匹配器,下一步最好是查看 Jest 如何让你 测试异步代码。
¥Once you've learned about the matchers that are available, a good next step is to check out how Jest lets you test asynchronous code.