预计·续3
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', );});
Note that, 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');});
.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) as expect(Object.is(received, expected)).toBe(true)
-
rewrite expect(received).not.toBe(expected) as expect(Object.is(received, expected)).toBe(false)
.toHaveBeenCalled()
Also under the alias: .toBeCalled()
Use .toHaveBeenCalled to ensure that a mock function got 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. 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 for 'lemon', but not for 'octopus', because 'octopus' flavour is really weird and why would anything be octopus-flavoured? You can do that with this test suite: 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.
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');});
Note: the nth argument must be positive integer starting from 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)
