预计·续1
When an assertion fails, the error message should give as much signal as necessary to the user so they can resolve their issue quickly. You should craft a precise failure message to make sure users of your custom assertions have a good developer experience. You should craft a precise failure message to make sure users of your custom assertions have a good developer experience.
Custom snapshot matchers
To use snapshot testing inside of your custom matcher you can import jest-snapshot and use it from within your matcher.
Here’s a snapshot matcher that trims a string to store for a given length, .toMatchTrimmedSnapshot(length):
const {toMatchSnapshot} = require('jest-snapshot');expect.extend({ toMatchTrimmedSnapshot(received, length) { return toMatchSnapshot.call( this, received.substring(0, length), 'toMatchTrimmedSnapshot', ); },});it('stores only 10 characters', () => { expect('extra long string oh my gerd').toMatchTrimmedSnapshot(10);});/*Stored snapshot will look like:exports[`stores only 10 characters: toMatchTrimmedSnapshot 1`] = `"extra long"`;*/
It’s also possible to create custom matchers for inline snapshots, the snapshots will be correctly added to the custom matchers. It’s also possible to create custom matchers for inline snapshots, the snapshots will be correctly added to the custom matchers. However, inline snapshot will always try to append to the first argument or the second when the first argument is the property matcher, so it’s not possible to accept custom arguments in the custom matchers.
const {toMatchInlineSnapshot} = require('jest-snapshot');expect.extend({ toMatchTrimmedInlineSnapshot(received, ...rest) { return toMatchInlineSnapshot.call(this, received.substring(0, 10), ...rest); },});it('stores only 10 characters', () => { expect('extra long string oh my gerd').toMatchTrimmedInlineSnapshot(); /* The snapshot will be added inline like expect('extra long string oh my gerd').toMatchTrimmedInlineSnapshot( `"extra long"` ); */});
async
If your custom inline snapshot matcher is async i.e. uses async-await you might encounter an error like “Multiple inline snapshots for the same call are not supported”. Jest needs additional context information to find where the custom inline snapshot matcher was used to update the snapshots properly.
const {toMatchInlineSnapshot} = require('jest-snapshot');expect.extend({ async toMatchObservationInlineSnapshot(fn, ...rest) { // The error (and its stacktrace) must be created before any `await` this.error = new Error(); // The implementation of `observe` doesn't matter. // It only matters that the custom snapshot matcher is async. const observation = await observe(async () => { await fn(); }); return toMatchInlineSnapshot.call(this, recording, ...rest); },});it('observes something', async () => { await expect(async () => { return 'async action'; }).toMatchTrimmedInlineSnapshot(); /* The snapshot will be added inline like await expect(async () => { return 'async action'; }).toMatchTrimmedInlineSnapshot(`"async action"`); */});
Bail out
Usually jest tries to match every snapshot that is expected in a test.
Sometimes it might not make sense to continue the test if a prior snapshot failed. For example, when you make snapshots of a state-machine after various transitions you can abort the test once one transition produced the wrong state.
In that case you can implement a custom snapshot matcher that throws on the first mismatch instead of collecting every mismatch.
const {toMatchInlineSnapshot} = require('jest-snapshot');expect.extend({ toMatchStateInlineSnapshot(...args) { this.dontThrow = () => {}; return toMatchInlineSnapshot.call(this, ...args); },});let state = 'initial';function transition() { // Typo in the implementation should cause the test to fail if (state === 'INITIAL') { state = 'pending'; } else if (state === 'pending') { state = 'done'; }}it('transitions as expected', () => { expect(state).toMatchStateInlineSnapshot(`"initial"`); transition(); // Already produces a mismatch. No point in continuing the test. expect(state).toMatchStateInlineSnapshot(`"loading"`); transition(); expect(state).toMatchStateInlineSnapshot(`"done"`);});
expect.anything()
expect.anything() matches anything but null or undefined. You can use it inside toEqual or toBeCalledWith instead of a literal value. For example, if you want to check that a mock function is called with a non-null argument: You can use it inside toEqual or toBeCalledWith instead of a literal value. For example, if you want to check that a mock function is called with a non-null argument:
test('map calls its argument with a non-null argument', () => { const mock = jest.fn(); [1].map(x => mock(x)); expect(mock).toBeCalledWith(expect.anything());});
expect.any(constructor)
expect.any(constructor) matches anything that was created with the given constructor. You can use it inside toEqual or toBeCalledWith instead of a literal value. For example, if you want to check that a mock function is called with a number:
function randocall(fn) { return fn(Math.floor(Math.random() * 6 + 1));}test('randocall calls its callback with a number', () => { const mock = jest.fn(); randocall(mock); expect(mock).toBeCalledWith(expect.any(Number));});
expect.arrayContaining(array)
expect.arrayContaining(array) matches a received array which contains all of the elements in the expected array. That is, the expected array is a subset of the received array. Therefore, it matches a received array which contains elements that are not in the expected array. That is, the expected array is a subset of the received array. Therefore, it matches a received array which contains elements that are not in the expected array.
You can use it instead of a literal value:
-
in toEqual or toBeCalledWith
-
to match a property in objectContaining or toMatchObject
describe('arrayContaining', () => { const expected = ['Alice', 'Bob']; it('matches even if received contains additional elements', () => { expect(['Alice', 'Bob', 'Eve']).toEqual(expect.arrayContaining(expected)); }); it('does not match if received does not contain expected elements', () => { expect(['Bob', 'Eve']).not.toEqual(expect.arrayContaining(expected)); });});
describe('Beware of a misunderstanding! describe('Beware of a misunderstanding! A sequence of dice rolls', () => { const expected = [1, 2, 3, 4, 5, 6]; it('matches even with an unexpected number 7', () => { expect([4, 1, 6, 7, 3, 5, 2, 5, 4, 6]).toEqual( expect.arrayContaining(expected), ); }); it('does not match without an expected number 2', () => { expect([4, 1, 6, 7, 3, 5, 7, 5, 4, 6]).not.toEqual( expect.arrayContaining(expected), ); });});
expect.assertions(number)
expect.assertions(number) verifies that a certain number of assertions are called during a test. This is often useful when testing asynchronous code, in order to make sure that assertions in a callback actually got called. This is often useful when testing asynchronous code, in order to make sure that assertions in a callback actually got called.
For example, let’s say that we have a function doAsync that receives two callbacks callback1 and callback2, it will asynchronously call both of them in an unknown order. We can test this with: We can test this with:
test('doAsync calls both callbacks', async () => { expect.assertions(2); function callback1(data) { expect(data).toBeTruthy(); } function callback2(data) { expect(data).toBeTruthy(); } await doAsync(callback1, callback2);});
The expect.assertions(2) call ensures that both callbacks actually get called.
