Expect 断言
在写测试的时候,我们经常需要检查值是否满足指定的条件。 expect
让你可以使用不同的“匹配器”去验证不同类型的东西。
For additional Jest matchers maintained by the Jest Community check out jest-extended
.
The TypeScript examples from this page will only work as documented if you explicitly import Jest APIs:
import {expect, jest, test} from '@jest/globals';
Consult the Getting Started guide for details on how to setup Jest with TypeScript.
参考
- Expect 断言
- Modifiers
- Matchers
.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)
- Asymmetric Matchers
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)
- Assertion Count
- Extend Utilities
Expect 断言
expect(value)
判断一个值是否满足条件,你会使用到expect
函数。 但你很少会单独调用expect
函数, 因为你通常会结合expect
和匹配器函数来断言某个值。
下面是一个很容易理解的例子: 假设你有一个方法bestLaCroixFlavor()
,它应该返回字符串'grapefruit'
。 下面是如何测试:
test('the best flavor is grapefruit', () => {
expect(bestLaCroixFlavor()).toBe('grapefruit');
});
上述代码里的 toBe
就是我们所说的匹配器函数, 本篇文档下面的部分提供了很多不同的匹配器函数,了解它们可以帮助你测试更多不同的内容。
expect
的参数应该是被测代码的返回值,而匹配器接收的传入参数则是希望被测代码返回的值。 如果你将它们混合使用,你的测试仍然可以执行,但是测试失败的错误信息看起来会比较奇怪。
Modifiers
.not
If you know how to test something, .not
lets you test its opposite. For example, this code tests that the best La Croix flavor is not coconut: For example, this code tests that the best La Croix flavor is not coconut:
test('the best flavor is not coconut', () => {
expect(bestLaCroixFlavor()).not.toBe('coconut');
});
.resolves
Use resolves
to unwrap the value of a fulfilled promise so any other matcher can be chained. If the promise is rejected the assertion fails. If the promise is rejected the assertion fails.
For example, this code tests that the promise resolves and that the resulting value is 'lemon'
:
test('resolves to lemon', () => {
// make sure to add a return statement
return expect(Promise.resolve('lemon')).resolves.toBe('lemon');
});
Since you are still testing promises, the test is still asynchronous. Note that, since you are still testing promises, the test is still asynchronous. Hence, you will need to tell Jest to wait by returning the unwrapped assertion.
Alternatively, you can use async/await
in combination with .resolves
:
test('resolves to lemon', async () => {
await expect(Promise.resolve('lemon')).resolves.toBe('lemon');
await expect(Promise.resolve('lemon')).resolves.not.toBe('octopus');
});
.rejects
Use .rejects
to unwrap the reason of a rejected promise so any other matcher can be chained. If the promise is fulfilled the assertion fails. If the promise is fulfilled the assertion fails.
For example, this code tests that the promise rejects with reason 'octopus'
:
test('rejects to octopus', () => {
// make sure to add a return statement
return expect(Promise.reject(new Error('octopus'))).rejects.toThrow(
'octopus',
);
});
Since you are still testing promises, the test is still asynchronous. Note that, since you are still testing promises, the test is still asynchronous. Hence, you will need to tell Jest to wait by returning the unwrapped assertion.
Alternatively, you can use async/await
in combination with .rejects
.
test('rejects to octopus', async () => {
await expect(Promise.reject(new Error('octopus'))).rejects.toThrow('octopus');
});
Matchers
.toBe(value)
Use .toBe
to compare primitive values or to check referential identity of object instances. It calls Object.is
to compare values, which is even better for testing than ===
strict equality operator.
For example, this code will validate some properties of the can
object:
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');
});
});
Don't use .toBe
with floating-point numbers. For example, due to rounding, in JavaScript 0.2 + 0.1
is not strictly equal to 0.3
. Don't use .toBe
with floating-point numbers. For example, due to rounding, in JavaScript 0.2 + 0.1
is not strictly equal to 0.3
. If you have floating point numbers, try .toBeCloseTo
instead.
Although the .toBe
matcher checks referential identity, it reports a deep comparison of values if the assertion fails. If differences between properties do not help you to understand why a test fails, especially if the report is large, then you might move the comparison into the expect
function. For example, to assert whether or not elements are the same instance: If differences between properties do not help you to understand why a test fails, especially if the report is large, then you might move the comparison into the expect
function. For example, use equals
method of Buffer
class to assert whether or not buffers contain the same content: For example, to assert whether or not elements are the same instance:
- rewrite
expect(received).toBe(expected)
asexpect(Object.is(received, expected)).toBe(true)
- rewrite
expect(received).not.toBe(expected)
asexpect(Object.is(received, expected)).toBe(false)
.toHaveBeenCalled()
Also under the alias: .toBeCalled()
Use .toHaveBeenCalled
to ensure that a mock function was called.
For example, let's say you have a drinkAll(drink, flavour)
function that takes a drink
function and applies it to all available beverages. You might want to check that drink
gets called. You can do that with this test suite:
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();
});
});
.toHaveBeenCalledTimes(number)
Also under the alias: .toBeCalledTimes(number)
Use .toHaveBeenCalledTimes
to ensure that a mock function got called exact number of times.
For example, let's say you have a drinkEach(drink, Array<flavor>)
function that takes a drink
function and applies it to array of passed beverages. You might want to check that drink function was called exact number of times. You can do that with this test suite: You might want to check that drink function was called exact number of times. You can do that with this test suite:
test('drinkEach drinks each drink', () => {
const drink = jest.fn();
drinkEach(drink, ['lemon', 'octopus']);
expect(drink).toHaveBeenCalledTimes(2);
});
.toHaveBeenCalledWith(arg1, arg2, ...)
Also under the alias: .toBeCalledWith()
Use .toHaveBeenCalledWith
to ensure that a mock function was called with specific arguments. The arguments are checked with the same algorithm that .toEqual
uses.
For example, let's say that you can register a beverage with a register
function, and applyToAll(f)
should apply the function f
to all registered beverages. To make sure this works, you could write: To make sure this works, you could write:
test('registration applies correctly to orange La Croix', () => {
const beverage = new LaCroix('orange');
register(beverage);
const f = jest.fn();
applyToAll(f);
expect(f).toHaveBeenCalledWith(beverage);
});
.toHaveBeenLastCalledWith(arg1, arg2, ...)
Also under the alias: .lastCalledWith(arg1, arg2, ...)
If you have a mock function, you can use .toHaveBeenLastCalledWith
to test what arguments it was last called with. For example, let's say you have a applyToAllFlavors(f)
function that applies f
to a bunch of flavors, and you want to ensure that when you call it, the last flavor it operates on is 'mango'
. You can write: For example, let's say you have a applyToAllFlavors(f)
function that applies f
to a bunch of flavors, and you want to ensure that when you call it, the last flavor it operates on is 'mango'
. You can write:
test('applying to all flavors does mango last', () => {
const drink = jest.fn();
applyToAllFlavors(drink);
expect(drink).toHaveBeenLastCalledWith('mango');
});
.toHaveBeenNthCalledWith(nthCall, arg1, arg2, ....)
Also under the alias: .nthCalledWith(nthCall, arg1, arg2, ...)
If you have a mock function, you can use .toHaveBeenNthCalledWith
to test what arguments it was nth called with. For example, let's say you have a drinkEach(drink, Array<flavor>)
function that applies f
to a bunch of flavors, and you want to ensure that when you call it, the first flavor it operates on is 'lemon'
and the second one is 'octopus'
. You can write:
test('drinkEach drinks each drink', () => {
const drink = jest.fn();
drinkEach(drink, ['lemon', 'octopus']);
expect(drink).toHaveBeenNthCalledWith(1, 'lemon');
expect(drink).toHaveBeenNthCalledWith(2, 'octopus');
});
第 n 个参数必须是从1开始的正整数
.toHaveReturned()
Also under the alias: .toReturn()
If you have a mock function, you can use .toHaveReturned
to test that the mock function successfully returned (i.e., did not throw an error) at least one time. For example, let's say you have a mock drink
that returns true
. You can write: For example, let's say you have a mock drink
that returns true
. You can write:
test('drinks returns', () => {
const drink = jest.fn(() => true);
drink();
expect(drink).toHaveReturned();
});
.toHaveReturnedTimes(number)
Also under the alias: .toReturnTimes(number)
Use .toHaveReturnedTimes
to ensure that a mock function returned successfully (i.e., did not throw an error) an exact number of times. Any calls to the mock function that throw an error are not counted toward the number of times the function returned. Any calls to the mock function that throw an error are not counted toward the number of times the function returned.
For example, let's say you have a mock drink
that returns true
. You can write:
test('drink returns twice', () => {
const drink = jest.fn(() => true);
drink();
drink();
expect(drink).toHaveReturnedTimes(2);
});
.toHaveReturnedWith(value)
Also under the alias: .toReturnWith(value)
Use .toHaveReturnedWith
to ensure that a mock function returned a specific value.
For example, let's say you have a mock drink
that returns the name of the beverage that was consumed. You can write: You can write:
test('drink returns La Croix', () => {
const beverage = {name: 'La Croix'};
const drink = jest.fn(beverage => beverage.name);
drink(beverage);
expect(drink).toHaveReturnedWith('La Croix');
});
.toHaveLastReturnedWith(value)
Also under the alias: .lastReturnedWith(value)
Use .toHaveLastReturnedWith
to test the specific value that a mock function last returned. Use .toHaveLastReturnedWith
to test the specific value that a mock function last returned. If the last call to the mock function threw an error, then this matcher will fail no matter what value you provided as the expected return value.
For example, let's say you have a mock drink
that returns the name of the beverage that was consumed. You can write: You can write:
test('drink returns La Croix (Orange) last', () => {
const beverage1 = {name: 'La Croix (Lemon)'};
const beverage2 = {name: 'La Croix (Orange)'};
const drink = jest.fn(beverage => beverage.name);
drink(beverage1);
drink(beverage2);
expect(drink).toHaveLastReturnedWith('La Croix (Orange)');
});
.toHaveNthReturnedWith(nthCall, value)
Also under the alias: .nthReturnedWith(nthCall, value)
Use .toHaveNthReturnedWith
to test the specific value that a mock function returned for the nth call. Use .toHaveNthReturnedWith
to test the specific value that a mock function returned for the nth call. If the nth call to the mock function threw an error, then this matcher will fail no matter what value you provided as the expected return value.
For example, let's say you have a mock drink
that returns the name of the beverage that was consumed. You can write: You can write:
test('drink returns expected nth calls', () => {
const beverage1 = {name: 'La Croix (Lemon)'};
const beverage2 = {name: 'La Croix (Orange)'};
const drink = jest.fn(beverage => beverage.name);
drink(beverage1);
drink(beverage2);
expect(drink).toHaveNthReturnedWith(1, 'La Croix (Lemon)');
expect(drink).toHaveNthReturnedWith(2, 'La Croix (Orange)');
});
第 n 个参数必须是从1开始的正整数
.toHaveLength(number)
Use .toHaveLength
to check that an object has a .length
property and it is set to a certain numeric value.
This is especially useful for checking arrays or strings size.
expect([1, 2, 3]).toHaveLength(3);
expect('abc').toHaveLength(3);
expect('').not.toHaveLength(5);
.toHaveProperty(keyPath, value?)
Use .toHaveProperty
to check if property at provided reference keyPath
exists for an object. Use .toHaveProperty
to check if property at provided reference keyPath
exists for an object. For checking deeply nested properties in an object you may use dot notation or an array containing the keyPath for deep references.
You can provide an optional value
argument to compare the received property value (recursively for all properties of object instances, also known as deep equality, like the toEqual
matcher).
The following example contains a houseForSale
object with nested properties. We are using toHaveProperty
to check for the existence and values of various properties in the object. We are using toHaveProperty
to check for the existence and values of various properties in the object.
// Object containing house features to be tested
const houseForSale = {
bath: true,
bedrooms: 4,
kitchen: {
amenities: ['oven', 'stove', 'washer'],
area: 20,
wallColor: 'white',
'nice.oven': true,
},
livingroom: {
amenities: [
{
couch: [
['large', {dimensions: [20, 20]}],
['small', {dimensions: [10, 10]}],
],
},
],
},
'ceiling.height': 2,
};
test('this house has my desired features', () => {
// Example Referencing
expect(houseForSale).toHaveProperty('bath');
expect(houseForSale).toHaveProperty('bedrooms', 4);
expect(houseForSale).not.toHaveProperty('pool');
// Deep referencing using dot notation
expect(houseForSale).toHaveProperty('kitchen.area', 20);
expect(houseForSale).toHaveProperty('kitchen.amenities', [
'oven',
'stove',
'washer',
]);
expect(houseForSale).not.toHaveProperty('kitchen.open');
// Deep referencing using an array containing the keyPath
expect(houseForSale).toHaveProperty(['kitchen', 'area'], 20);
expect(houseForSale).toHaveProperty(
['kitchen', 'amenities'],
['oven', 'stove', 'washer'],
);
expect(houseForSale).toHaveProperty(['kitchen', 'amenities', 0], 'oven');
expect(houseForSale).toHaveProperty(
'livingroom.amenities[0].couch[0][1].dimensions[0]',
20,
);
expect(houseForSale).toHaveProperty(['kitchen', 'nice.oven']);
expect(houseForSale).not.toHaveProperty(['kitchen', 'open']);
// Referencing keys with dot in the key itself
expect(houseForSale).toHaveProperty(['ceiling.height'], 'tall');
});
.toBeCloseTo(number, numDigits?)
Use toBeCloseTo
to compare floating point numbers for approximate equality.
The optional numDigits
argument limits the number of digits to check after the decimal point. The optional numDigits
argument limits the number of digits to check after the decimal point. For the default value 2
, the test criterion is Math.abs(expected - received) < 0.005
(that is, 10 ** -2 / 2
).
Intuitive equality comparisons often fail, because arithmetic on decimal (base 10) values often have rounding errors in limited precision binary (base 2) representation. For example, this test fails: For example, this test fails:
test('adding works sanely with decimals', () => {
expect(0.2 + 0.1).toBe(0.3); // Fails!
});
});
It fails because in JavaScript, 0.2 + 0.1
is actually 0.30000000000000004
.
For example, this test passes with a precision of 5 digits:
test('adding works sanely with decimals', () => {
expect(0.2 + 0.1).toBeCloseTo(0.3, 5);
});
Because floating point errors are the problem that toBeCloseTo
solves, it does not support big integer values.
.toBeDefined()
Use .toBeDefined
to check that a variable is not undefined. Use .toBeDefined
to check that a variable is not undefined. For example, if you want to check that a function fetchNewFlavorIdea()
returns something, you can write:
test('there is a new flavor idea', () => {
expect(fetchNewFlavorIdea()).toBeDefined();
});
You could write expect(fetchNewFlavorIdea()).not.toBe(undefined)
, but it's better practice to avoid referring to undefined
directly in your code.
.toBeFalsy()
Use .toBeFalsy
when you don't care what a value is and you want to ensure a value is false in a boolean context. For example, let's say you have some application code that looks like: For example, let's say you have some application code that looks like:
drinkSomeLaCroix();
if (!getErrors()) {
drinkMoreLaCroix();
}
You may not care what getErrors
returns, specifically - it might return false
, null
, or 0
, and your code would still work. So if you want to test there are no errors after drinking some La Croix, you could write: So if you want to test there are no errors after drinking some La Croix, you could write:
test('drinking La Croix does not lead to errors', () => {
drinkSomeLaCroix();
expect(getErrors()).toBeFalsy();
});
In JavaScript, there are six falsy values: false
, 0
, ''
, null
, undefined
, and NaN
. Everything else is truthy. Everything else is truthy.
.toBeGreaterThan(number | bigint)
Use toBeGreaterThan
to compare received > expected
for number or big integer values. Use toBeGreaterThan
to compare received > expected
for number or big integer values. For example, test that ouncesPerCan()
returns a value of more than 10 ounces:
test('ounces per can is more than 10', () => {
expect(ouncesPerCan()).toBeGreaterThan(10);
});
.toBeGreaterThanOrEqual(number | bigint)
Use toBeGreaterThanOrEqual
to compare received >= expected
for number or big integer values. For example, test that ouncesPerCan()
returns a value of at least 12 ounces: For example, test that ouncesPerCan()
returns a value of at least 12 ounces:
test('ounces per can is at least 12', () => {
expect(ouncesPerCan()).toBeGreaterThanOrEqual(12);
});
.toBeLessThan(number | bigint)
Use toBeLessThan
to compare received < expected
for number or big integer values. Use toBeLessThan
to compare received < expected
for number or big integer values. For example, test that ouncesPerCan()
returns a value of less than 20 ounces:
test('ounces per can is less than 20', () => {
expect(ouncesPerCan()).toBeLessThan(20);
});
.toBeLessThanOrEqual(number | bigint)
Use toBeLessThanOrEqual
to compare received <= expected
for number or big integer values. For example, test that ouncesPerCan()
returns a value of at most 12 ounces: For example, test that ouncesPerCan()
returns a value of at most 12 ounces:
test('ounces per can is at most 12', () => {
expect(ouncesPerCan()).toBeLessThanOrEqual(12);
});
.toBeInstanceOf(Class)
Use .toBeInstanceOf(Class)
to check that an object is an instance of a class. This matcher uses instanceof
underneath. This matcher uses instanceof
underneath.
class A {}
expect(new A()).toBeInstanceOf(A);
expect(() => {}).toBeInstanceOf(Function);
expect(new A()).toBeInstanceOf(Function); // throws
.toBeNull()
.toBeNull()
is the same as .toBe(null)
but the error messages are a bit nicer. So use .toBeNull()
when you want to check that something is null. So use .toBeNull()
when you want to check that something is null.
function bloop() {
return null;
}
test('bloop returns null', () => {
expect(bloop()).toBeNull();
});
.toBeTruthy()
Use .toBeTruthy
when you don't care what a value is and you want to ensure a value is true in a boolean context. For example, let's say you have some application code that looks like: For example, let's say you have some application code that looks like:
drinkSomeLaCroix();
if (thirstInfo()) {
drinkMoreLaCroix();
}
You may not care what thirstInfo
returns, specifically - it might return true
or a complex object, and your code would still work. So if you want to test that thirstInfo
will be truthy after drinking some La Croix, you could write: So if you want to test that thirstInfo
will be truthy after drinking some La Croix, you could write:
test('drinking La Croix leads to having thirst info', () => {
drinkSomeLaCroix();
expect(thirstInfo()).toBeTruthy();
});
In JavaScript, there are six falsy values: false
, 0
, ''
, null
, undefined
, and NaN
. Everything else is truthy. Everything else is truthy.
.toBeUndefined()
Use .toBeUndefined
to check that a variable is undefined. Use .toBeUndefined
to check that a variable is undefined. For example, if you want to check that a function bestDrinkForFlavor(flavor)
returns undefined
for the 'octopus'
flavor, because there is no good octopus-flavored drink:
test('the best drink for octopus flavor is undefined', () => {
expect(bestDrinkForFlavor('octopus')).toBeUndefined();
});
You could write expect(bestDrinkForFlavor('octopus')).toBe(undefined)
, but it's better practice to avoid referring to undefined
directly in your code.
.toBeNaN()
Use .toBeNaN
when checking a value is NaN
.
test('passes when value is NaN', () => {
expect(NaN).toBeNaN();
expect(1).not.toBeNaN();
});
.toContain(item)
Use .toContain
when you want to check that an item is in an array. For testing the items in the array, this uses ===
, a strict equality check. .toContain
can also check whether a string is a substring of another string. For testing the items in the array, this uses ===
, a strict equality check. .toContain
can also check whether a string is a substring of another string.
For example, if getAllFlavors()
returns an array of flavors and you want to be sure that lime
is in there, you can write:
test('the flavor list contains lime', () => {
expect(getAllFlavors()).toContain('lime');
});
This matcher also accepts others iterables such as strings, sets, node lists and HTML collections.
.toContainEqual(item)
Use .toContainEqual
when you want to check that an item with a specific structure and values is contained in an array. For testing the items in the array, this matcher recursively checks the equality of all fields, rather than checking for object identity. For testing the items in the array, this matcher recursively checks the equality of all fields, rather than checking for object identity.
describe('my beverage', () => {
test('is delicious and not sour', () => {
const myBeverage = {delicious: true, sour: false};
expect(myBeverages()).toContainEqual(myBeverage);
});
});
.toEqual(value)
Use .toEqual
to compare recursively all properties of object instances (also known as "deep" equality). It calls Object.is
to compare primitive values, which is even better for testing than ===
strict equality operator. Use .toBe
to compare primitive values or to check referential identity of object instances. It calls Object.is
to compare values, which is even better for testing than ===
strict equality operator.
For example, .toEqual
and .toBe
behave differently in this test suite, so all the tests pass:
const can1 = {
flavor: 'grapefruit',
ounces: 12,
};
const can2 = {
flavor: 'grapefruit',
ounces: 12,
};
describe('the La Croix cans on my desk', () => {
test('have all the same properties', () => {
expect(can1).toEqual(can2);
});
test('are not the exact same can', () => {
expect(can1).not.toBe(can2);
});
});
toEqual
ignores object keys with undefined
properties, undefined
array items, array sparseness, or object type mismatch. To take these into account use .toStrictEqual
instead.
.toEqual
won't perform a deep equality check for two errors. Only the message
property of an Error is considered for equality. It is recommended to use the .toThrow
matcher for testing against errors.
If differences between properties do not help you to understand why a test fails, especially if the report is large, then you might move the comparison into the expect
function. For example, use equals
method of Buffer
class to assert whether or not buffers contain the same content: For example, use equals
method of Buffer
class to assert whether or not buffers contain the same content:
- rewrite
expect(received).toEqual(expected)
asexpect(received.equals(expected)).toBe(true)
- rewrite
expect(received).not.toEqual(expected)
asexpect(received.equals(expected)).toBe(false)
.toMatch(regexp | string)
Use .toMatch
to check that a string matches a regular expression.
For example, you might not know what exactly essayOnTheBestFlavor()
returns, but you know it's a really long string, and the substring grapefruit
should be in there somewhere. You can test this with: You can test this with:
describe('an essay on the best flavor', () => {
test('mentions grapefruit', () => {
expect(essayOnTheBestFlavor()).toMatch(/grapefruit/);
expect(essayOnTheBestFlavor()).toMatch(new RegExp('grapefruit'));
});
});
This matcher also accepts a string, which it will try to match:
describe('grapefruits are healthy', () => {
test('grapefruits are a fruit', () => {
expect('grapefruits').toMatch('fruit');
});
});
.toMatchObject(object)
Use .toMatchObject
to check that a JavaScript object matches a subset of the properties of an object. It will match received objects with properties that are not in the expected object. It will match received objects with properties that are not in the expected object.
You can also pass an array of objects, in which case the method will return true only if each object in the received array matches (in the toMatchObject
sense described above) the corresponding object in the expected array. This is useful if you want to check that two arrays match in their number of elements, as opposed to arrayContaining
, which allows for extra elements in the received array. This is useful if you want to check that two arrays match in their number of elements, as opposed to arrayContaining
, which allows for extra elements in the received array.
You can match properties against values or against matchers.
const houseForSale = {
bath: true,
bedrooms: 4,
kitchen: {
amenities: ['oven', 'stove', 'washer'],
area: 20,
wallColor: 'white',
},
};
const desiredHouse = {
bath: true,
kitchen: {
amenities: ['oven', 'stove', 'washer'],
wallColor: expect.stringMatching(/white|yellow/),
},
};
test('the house has my desired features', () => {
expect(houseForSale).toMatchObject(desiredHouse);
});
describe('toMatchObject applied to arrays', () => {
test('the number of elements must match exactly', () => {
expect([{foo: 'bar'}, {baz: 1}]).toMatchObject([{foo: 'bar'}, {baz: 1}]);
});
test('.toMatchObject is called for each elements, so extra object properties are okay', () => {
expect([{foo: 'bar'}, {baz: 1, extra: 'quux'}]).toMatchObject([
{foo: 'bar'},
{baz: 1},
]);
});
});
.toMatchSnapshot(propertyMatchers?, hint?)
This ensures that a value matches the most recent snapshot. This ensures that a value matches the most recent snapshot. Check out the Snapshot Testing guide for more information.
You can provide an optional propertyMatchers
object argument, which has asymmetric matchers as values of a subset of expected properties, if the received value will be an object instance. It is like toMatchObject
with flexible criteria for a subset of properties, followed by a snapshot test as exact criteria for the rest of the properties. It is like toMatchObject
with flexible criteria for a subset of properties, followed by a snapshot test as exact criteria for the rest of the properties.
You can provide an optional hint
string argument that is appended to the test name. You can provide an optional hint
string argument that is appended to the test name. Although Jest always appends a number at the end of a snapshot name, short descriptive hints might be more useful than numbers to differentiate multiple snapshots in a single it
or test
block. Jest sorts snapshots by name in the corresponding .snap
file. Jest sorts snapshots by name in the corresponding .snap
file.
.toMatchInlineSnapshot(propertyMatchers?, inlineSnapshot)
Ensures that a value matches the most recent snapshot.
You can provide an optional propertyMatchers
object argument, which has asymmetric matchers as values of a subset of expected properties, if the received value will be an object instance. It is like toMatchObject
with flexible criteria for a subset of properties, followed by a snapshot test as exact criteria for the rest of the properties. It is like toMatchObject
with flexible criteria for a subset of properties, followed by a snapshot test as exact criteria for the rest of the properties.
Jest adds the inlineSnapshot
string argument to the matcher in the test file (instead of an external .snap
file) the first time that the test runs.
Check out the section on Inline Snapshots for more info.
.toStrictEqual(value)
Use .toStrictEqual
to test that objects have the same structure and type.
Differences from .toEqual
:
- keys with
undefined
properties are checked, e.g.{a: undefined, b: 2}
will not equal{b: 2}
; undefined
items are taken into account, e.g.[2]
will not equal[2, undefined]
;- array sparseness is checked, e.g.
[, 1]
will not equal[undefined, 1]
; - object types are checked, e.g. a class instance with fields
a
andb
will not equal a literal object with fieldsa
andb
.
class LaCroix {
constructor(flavor) {
this.flavor = flavor;
}
}
describe('the La Croix cans on my desk', () => {
test('are not semantically the same', () => {
expect(new LaCroix('lemon')).toEqual({flavor: 'lemon'});
expect(new LaCroix('lemon')).not.toStrictEqual({flavor: 'lemon'});
});
});
.toThrow(error?)
Also under the alias: .toThrowError(error?)
Use .toThrow
to test that a function throws when it is called. Use .toThrow
to test that a function throws when it is called. For example, if we want to test that drinkFlavor('octopus')
throws, because octopus flavor is too disgusting to drink, we could write:
test('throws on octopus', () => {
expect(() => {
drinkFlavor('octopus');
}).toThrow();
});
Tips:你必须使用外层函数包装测试代码,否则无法捕获错误且断言会失败。
You can provide an optional argument to test that a specific error is thrown:
- regular expression: error message matches the pattern
- string: error message includes the substring
- error object: error message is equal to the message property of the object
- error class: error object is instance of class
For example, let's say that drinkFlavor
is coded like this:
function drinkFlavor(flavor) {
if (flavor === 'octopus') {
throw new DisgustingFlavorError('yuck, octopus flavor');
}
// Do some other stuff
}