预期

当写测试时,你经常需要检查值是否满足指定的条件。 expect 让您可以访问一些“匹配器”,让您验证不同类型的东西。

对于由 Jest 社区维护的其他 Jest 匹配器,请查看 jest-extended

方法


参考

expect(value)

要测试一个值,你需要使用expect函数。 你大概率不需要自己调用expect。 相反,你通常会使用expect 配合 “matcher” 函数来“断言”某个值。

下面是一个很容易理解的例子: 假设你有一个方法bestLaCroixFlavor(),它应该返回字符串'grapefruit'。 下面是如何测试:

  1. test('the best flavor is grapefruit', () => {
  2. expect(bestLaCroixFlavor()).toBe('grapefruit');
  3. });

上述情况下的 toBe 就是我们所说的 “matcher” 函数 本篇文档下面的部分,提供了很多不同的 matcher 函数,可帮助您测试不同的内容。

expect的参数应该是你要测试的代码的返回值,所有传递给 matcher 的参数,应该为其期望值 如果你混合使用,您的测试仍然可以工作,但是测试失败时,错误信息看起来会比较奇怪。

expect.extend(matchers)

您可以使用expect.extend将自己的 matcher 添加到 Jest。 例如,假设您正在测试一个处理 number 的工具库,并且您经常断言某个数字在一个范围之内。 您可以将其抽象为toBeDivisibleBy matcher:

  1. expect.extend({
  2. toBeWithinRange(received, floor, ceiling) {
  3. const pass = received >= floor && received <= ceiling;
  4. if (pass) {
  5. return {
  6. message: () =>
  7. `expected ${received} not to be within range ${floor} - ${ceiling}`,
  8. pass: true,
  9. };
  10. } else {
  11. return {
  12. message: () =>
  13. `expected ${received} to be within range ${floor} - ${ceiling}`,
  14. pass: false,
  15. };
  16. }
  17. },
  18. });
  19. test('numeric ranges', () => {
  20. expect(100).toBeWithinRange(90, 110);
  21. expect(101).not.toBeWithinRange(0, 100);
  22. expect({apples: 6, bananas: 3}).toEqual({
  23. apples: expect.toBeWithinRange(1, 10),
  24. bananas: expect.not.toBeWithinRange(11, 20),
  25. });
  26. });
note" class="reference-link">预期 - 图4note

In TypeScript, when using @types/jest for example, you can declare the new toBeWithinRange matcher in the imported module like this:

  1. interface CustomMatchers<R = unknown> {
  2. toBeWithinRange(floor: number, ceiling: number): R;
  3. }
  4. declare global {
  5. namespace jest {
  6. interface Expect extends CustomMatchers {}
  7. interface Matchers<R> extends CustomMatchers<R> {}
  8. interface InverseAsymmetricMatchers extends CustomMatchers {}
  9. }
  10. }

异步 Matcher

expect.extension 也支持异步 Matcher。 异步匹配器返回了一个 Promise,因此您需要 await 返回值。 接下来我们给出一个例子来说明其用法。 我们将实现一个叫做 toBevisibleByExternalValue的 Matcher,在这个Matcher 中,可被外部值整除的值将被通过。

  1. expect.extend({
  2. async toBeDivisibleByExternalValue(received) {
  3. const externalValue = await getExternalValueFromRemoteSource();
  4. const pass = received % externalValue == 0;
  5. if (pass) {
  6. return {
  7. message: () =>
  8. `expected ${received} not to be divisible by ${externalValue}`,
  9. pass: true,
  10. };
  11. } else {
  12. return {
  13. message: () =>
  14. `expected ${received} to be divisible by ${externalValue}`,
  15. pass: false,
  16. };
  17. }
  18. },
  19. });
  20. test('is divisible by external value', async () => {
  21. await expect(100).toBeDivisibleByExternalValue();
  22. await expect(101).not.toBeDivisibleByExternalValue();
  23. });

自定义 Matcher API

Matcher 应该返回一个拥有 2 个属性的 object(或者返回一个 Promise,其返回值为拥有 2 个属性的 obect)。 pass表示是否匹配到,而 message 提供了一个没有参数的函数,在出现故障的情况下返回错误消息。 因此,当pass为false时,message应该返回当expect(x).yourMatcher()失败时的错误消息。 而当pass为true时, message应该返回当expect(x).not.yourMatcher()失败时的错误信息。

Matcher 被时,收到的第一个参数为 expect(x) 中的 x,第二、三个参数分别为 .yourMatcher(y, z) 中的 yz

  1. expect.extend({
  2. yourMatcher(x, y, z) {
  3. return {
  4. pass: true,
  5. message: () => '',
  6. };
  7. },
  8. });

在自定义 Matcher 中,可以通过 this 来访问下列帮助函数与属性:

this.isNot

一个布尔值,可以让你知道这个 matcher 之前是否调用了表示否定的 .not 修饰符,以便你提供给用户一个比较清晰和正确的 matcher 提示(参见示例代码)。

this.promise

一个字符串允许您显示一个清晰和正确的匹配器提示:

  • 'reject' 如果 matcher 被 Promise中的 .rejects 所调用
  • 'resolves' 如果 matcher 被 Promise中的 .resolves 所调用
  • '' 如果 matcher 没有被 Promise 修饰符调用

this.equals(a, b)

A boolean to let you know this matcher was called with an expand option. When Jest is called with the --expand flag, this.expand can be used to determine if Jest is expected to show full diffs and errors.

this.expand

A boolean to let you know this matcher was called with an expand option. When Jest is called with the --expand flag, this.expand can be used to determine if Jest is expected to show full diffs and errors.

this.utils

There are a number of helpful tools exposed on this.utils primarily consisting of the exports from jest-matcher-utils.

The most useful ones are matcherHint, printExpected and printReceived to format the error messages nicely. For example, take a look at the implementation for the toBe matcher:

  1. const {diff} = require('jest-diff');
  2. expect.extend({
  3. toBe(received, expected) {
  4. const options = {
  5. comment: 'Object.is equality',
  6. isNot: this.isNot,
  7. promise: this.promise,
  8. };
  9. const pass = Object.is(received, expected);
  10. const message = pass
  11. ? () =>
  12. // eslint-disable-next-line prefer-template
  13. this.utils.matcherHint('toBe', undefined, undefined, options) +
  14. '\n\n' +
  15. `Expected: not ${this.utils.printExpected(expected)}\n` +
  16. `Received: ${this.utils.printReceived(received)}`
  17. : () => {
  18. const diffString = diff(expected, received, {
  19. expand: this.expand,
  20. });
  21. return (
  22. // eslint-disable-next-line prefer-template
  23. this.utils.matcherHint('toBe', undefined, undefined, options) +
  24. '\n\n' +
  25. (diffString && diffString.includes('- Expect')
  26. ? `Difference:\n\n${diffString}`
  27. : `Expected: ${this.utils.printExpected(expected)}\n` +
  28. `Received: ${this.utils.printReceived(received)}`)
  29. );
  30. };
  31. return {actual: received, message, pass};
  32. },
  33. });

This will print something like this:

  1. expect(received).toBe(expected)
  2. Expected value to be (using Object.is):
  3. "banana"
  4. Received:
  5. "apple"

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):

  1. const {toMatchSnapshot} = require('jest-snapshot');
  2. expect.extend({
  3. toMatchTrimmedSnapshot(received, length) {
  4. return toMatchSnapshot.call(
  5. this,
  6. received.substring(0, length),
  7. 'toMatchTrimmedSnapshot',
  8. );
  9. },
  10. });
  11. it('stores only 10 characters', () => {
  12. expect('extra long string oh my gerd').toMatchTrimmedSnapshot(10);
  13. });
  14. /*
  15. Stored snapshot will look like:
  16. exports[`stores only 10 characters: toMatchTrimmedSnapshot 1`] = `"extra long"`;
  17. */

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.

  1. const {toMatchInlineSnapshot} = require('jest-snapshot');
  2. expect.extend({
  3. toMatchTrimmedInlineSnapshot(received, ...rest) {
  4. return toMatchInlineSnapshot.call(this, received.substring(0, 10), ...rest);
  5. },
  6. });
  7. it('stores only 10 characters', () => {
  8. expect('extra long string oh my gerd').toMatchTrimmedInlineSnapshot();
  9. /*
  10. The snapshot will be added inline like
  11. expect('extra long string oh my gerd').toMatchTrimmedInlineSnapshot(
  12. `"extra long"`
  13. );
  14. */
  15. });

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.

  1. const {toMatchInlineSnapshot} = require('jest-snapshot');
  2. expect.extend({
  3. async toMatchObservationInlineSnapshot(fn, ...rest) {
  4. // The error (and its stacktrace) must be created before any `await`
  5. this.error = new Error();
  6. // The implementation of `observe` doesn't matter.
  7. // It only matters that the custom snapshot matcher is async.
  8. const observation = await observe(async () => {
  9. await fn();
  10. });
  11. return toMatchInlineSnapshot.call(this, recording, ...rest);
  12. },
  13. });
  14. it('observes something', async () => {
  15. await expect(async () => {
  16. return 'async action';
  17. }).toMatchTrimmedInlineSnapshot();
  18. /*
  19. The snapshot will be added inline like
  20. await expect(async () => {
  21. return 'async action';
  22. }).toMatchTrimmedInlineSnapshot(`"async action"`);
  23. */
  24. });

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.

  1. const {toMatchInlineSnapshot} = require('jest-snapshot');
  2. expect.extend({
  3. toMatchStateInlineSnapshot(...args) {
  4. this.dontThrow = () => {};
  5. return toMatchInlineSnapshot.call(this, ...args);
  6. },
  7. });
  8. let state = 'initial';
  9. function transition() {
  10. // Typo in the implementation should cause the test to fail
  11. if (state === 'INITIAL') {
  12. state = 'pending';
  13. } else if (state === 'pending') {
  14. state = 'done';
  15. }
  16. }
  17. it('transitions as expected', () => {
  18. expect(state).toMatchStateInlineSnapshot(`"initial"`);
  19. transition();
  20. // Already produces a mismatch. No point in continuing the test.
  21. expect(state).toMatchStateInlineSnapshot(`"loading"`);
  22. transition();
  23. expect(state).toMatchStateInlineSnapshot(`"done"`);
  24. });

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:

  1. test('map calls its argument with a non-null argument', () => {
  2. const mock = jest.fn();
  3. [1].map(x => mock(x));
  4. expect(mock).toBeCalledWith(expect.anything());
  5. });

expect.any(constructor)

expect.any(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:

  1. class Cat {}
  2. function getCat(fn) {
  3. return fn(new Cat());
  4. }
  5. test('randocall calls its callback with a class instance', () => {
  6. const mock = jest.fn();
  7. getCat(mock);
  8. expect(mock).toBeCalledWith(expect.any(Cat));
  9. });
  10. function randocall(fn) {
  11. return fn(Math.floor(Math.random() * 6 + 1));
  12. }
  13. test('randocall calls its callback with a number', () => {
  14. const mock = jest.fn();
  15. randocall(mock);
  16. expect(mock).toBeCalledWith(expect.any(Number));
  17. });

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
  1. describe('arrayContaining', () => {
  2. const expected = ['Alice', 'Bob'];
  3. it('matches even if received contains additional elements', () => {
  4. expect(['Alice', 'Bob', 'Eve']).toEqual(expect.arrayContaining(expected));
  5. });
  6. it('does not match if received does not contain expected elements', () => {
  7. expect(['Bob', 'Eve']).not.toEqual(expect.arrayContaining(expected));
  8. });
  9. });
  1. describe('Beware of a misunderstanding! describe('Beware of a misunderstanding! A sequence of dice rolls', () => {
  2. const expected = [1, 2, 3, 4, 5, 6];
  3. it('matches even with an unexpected number 7', () => {
  4. expect([4, 1, 6, 7, 3, 5, 2, 5, 4, 6]).toEqual(
  5. expect.arrayContaining(expected),
  6. );
  7. });
  8. it('does not match without an expected number 2', () => {
  9. expect([4, 1, 6, 7, 3, 5, 7, 5, 4, 6]).not.toEqual(
  10. expect.arrayContaining(expected),
  11. );
  12. });
  13. });

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:

  1. test('doAsync calls both callbacks', () => {
  2. expect.assertions(2);
  3. function callback1(data) {
  4. expect(data).toBeTruthy();
  5. }
  6. function callback2(data) {
  7. expect(data).toBeTruthy();
  8. }
  9. doAsync(callback1, callback2);
  10. });

The expect.assertions(2) call ensures that both callbacks actually get called.

expect.closeTo(number, numDigits?)

expect.closeTo(number, numDigits?) is useful when comparing floating point numbers in object properties or array item. If you need to compare a number, please use .toBeCloseTo instead.

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).

For example, this test passes with a precision of 5 digits:

  1. test('compare float in object properties', () => {
  2. expect({
  3. title: '0.1 + 0.2',
  4. sum: 0.1 + 0.2,
  5. }).toEqual({
  6. title: '0.1 + 0.2',
  7. sum: expect.closeTo(0.3, 5),
  8. });
  9. });

expect.hasAssertions()

expect.hasAssertions() verifies that at least one assertion is 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 few functions that all deal with state. For example, let’s say that we have a few functions that all deal with state. prepareState calls a callback with a state object, validateState runs on that state object, and waitOnState returns a promise that waits until all prepareState callbacks complete. We can test this with: We can test this with:

  1. test('prepareState prepares a valid state', () => {
  2. expect.hasAssertions();
  3. prepareState(state => {
  4. expect(validateState(state)).toBeTruthy();
  5. });
  6. return waitOnState();
  7. });

The expect.hasAssertions() call ensures that the prepareState callback actually gets called.

expect.not.arrayContaining(array)

expect.not.arrayContaining(array) matches a received array which does not contain all of the elements in the expected array. That is, the expected array is not a subset of the received array. That is, the expected array is not a subset of the received array.

It is the inverse of expect.arrayContaining.

  1. describe('not.arrayContaining', () => {
  2. const expected = ['Samantha'];
  3. it('matches if the actual array does not contain the expected elements', () => {
  4. expect(['Alice', 'Bob', 'Eve']).toEqual(
  5. expect.not.arrayContaining(expected),
  6. );
  7. });
  8. });

expect.not.objectContaining(object)

expect.not.objectContaining(object) matches any received object that does not recursively match the expected properties. That is, the expected object is not a subset of the received object. Therefore, it matches a received object which contains properties that are not in the expected object. That is, the expected object is not a subset of the received object. Therefore, it matches a received object which contains properties that are not in the expected object.

It is the inverse of expect.objectContaining.

  1. describe('not.objectContaining', () => {
  2. const expected = {foo: 'bar'};
  3. it('matches if the actual object does not contain expected key: value pairs', () => {
  4. expect({bar: 'baz'}).toEqual(expect.not.objectContaining(expected));
  5. });
  6. });

expect.not.stringContaining(string)

expect.not.stringContaining(string) matches the received value if it is not a string or if it is a string that does not contain the exact expected string.

It is the inverse of expect.stringContaining.

  1. describe('not.stringContaining', () => {
  2. const expected = 'Hello world!';
  3. it('matches if the received value does not contain the expected substring', () => {
  4. expect('How are you?').toEqual(expect.not.stringContaining(expected));
  5. });
  6. });

expect.not.stringMatching(string | regexp)

expect.not.stringMatching(string | regexp) matches the received value if it is not a string or if it is a string that does not match the expected string or regular expression.

It is the inverse of expect.stringMatching.

  1. describe('not.stringMatching', () => {
  2. const expected = /Hello world!/;
  3. it('matches if the received value does not match the expected regex', () => {
  4. expect('How are you?').toEqual(expect.not.stringMatching(expected));
  5. });
  6. });

expect.objectContaining(object)

expect.objectContaining(object) matches any received object that recursively matches the expected properties. That is, the expected object is a subset of the received object. expect.objectContaining(object) matches any received object that recursively matches the expected properties. That is, the expected object is a subset of the received object. Therefore, it matches a received object which contains properties that are present in the expected object.

Instead of literal property values in the expected object, you can use matchers, expect.anything(), and so on.

For example, let’s say that we expect an onPress function to be called with an Event object, and all we need to verify is that the event has event.x and event.y properties. We can do that with: We can do that with:

  1. test('onPress gets called with the right thing', () => {
  2. const onPress = jest.fn();
  3. simulatePresses(onPress);
  4. expect(onPress).toBeCalledWith(
  5. expect.objectContaining({
  6. x: expect.any(Number),
  7. y: expect.any(Number),
  8. }),
  9. );
  10. });

expect.stringContaining(string)

expect.stringContaining(string) matches the received value if it is a string that contains the exact expected string.

expect.stringMatching(string | regexp)

expect.stringMatching(string | regexp) matches the received value if it is a string that matches the expected string or regular expression.

You can use it instead of a literal value:

  • in toEqual or toBeCalledWith
  • to match an element in arrayContaining
  • to match a property in objectContaining or toMatchObject

This example also shows how you can nest multiple asymmetric matchers, with expect.stringMatching inside the expect.arrayContaining.

  1. describe('stringMatching in arrayContaining', () => {
  2. const expected = [
  3. expect.stringMatching(/^Alic/),
  4. expect.stringMatching(/^[BR]ob/),
  5. ];
  6. it('matches even if received contains additional elements', () => {
  7. expect(['Alicia', 'Roberto', 'Evelina']).toEqual(
  8. expect.arrayContaining(expected),
  9. );
  10. });
  11. it('does not match if received does not contain expected elements', () => {
  12. expect(['Roberto', 'Evelina']).not.toEqual(
  13. expect.arrayContaining(expected),
  14. );
  15. });
  16. });

expect.addSnapshotSerializer(serializer)

You can call expect.addSnapshotSerializer to add a module that formats application-specific data structures.

For an individual test file, an added module precedes any modules from snapshotSerializers configuration, which precede the default snapshot serializers for built-in JavaScript types and for React elements. The last module added is the first module tested. The last module added is the first module tested.

  1. import serializer from 'my-serializer-module';
  2. expect.addSnapshotSerializer(serializer);
  3. // affects expect(value).toMatchSnapshot() assertions in the test file

If you add a snapshot serializer in individual test files instead of adding it to snapshotSerializers configuration:

  • You make the dependency explicit instead of implicit.
  • You avoid limits to configuration that might cause you to eject from create-react-app.

See configuring Jest for more information.

.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:

  1. test('the best flavor is not coconut', () => {
  2. expect(bestLaCroixFlavor()).not.toBe('coconut');
  3. });

.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':

  1. test('resolves to lemon', () => {
  2. // make sure to add a return statement
  3. return expect(Promise.resolve('lemon')).resolves.toBe('lemon');
  4. });

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 .resolves:

  1. test('resolves to lemon', async () => {
  2. await expect(Promise.resolve('lemon')).resolves.toBe('lemon');
  3. await expect(Promise.resolve('lemon')).resolves.not.toBe('octopus');
  4. });

.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':

  1. test('rejects to octopus', () => {
  2. // make sure to add a return statement
  3. return expect(Promise.reject(new Error('octopus'))).rejects.toThrow(
  4. 'octopus',
  5. );
  6. });

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.

  1. test('rejects to octopus', async () => {
  2. await expect(Promise.reject(new Error('octopus'))).rejects.toThrow('octopus');
  3. });

.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:

  1. const can = {
  2. name: 'pamplemousse',
  3. ounces: 12,
  4. };
  5. describe('the can', () => {
  6. test('has 12 ounces', () => {
  7. expect(can.ounces).toBe(12);
  8. });
  9. test('has a sophisticated name', () => {
  10. expect(can.name).toBe('pamplemousse');
  11. });
  12. });

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 .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 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:

  1. function drinkAll(callback, flavour) {
  2. if (flavour !== 'octopus') {
  3. callback(flavour);
  4. }
  5. }
  6. describe('drinkAll', () => {
  7. test('drinks something lemon-flavoured', () => {
  8. const drink = jest.fn();
  9. drinkAll(drink, 'lemon');
  10. expect(drink).toHaveBeenCalled();
  11. });
  12. test('does not drink something octopus-flavoured', () => {
  13. const drink = jest.fn();
  14. drinkAll(drink, 'octopus');
  15. expect(drink).not.toHaveBeenCalled();
  16. });
  17. });

.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:

  1. test('drinkEach drinks each drink', () => {
  2. const drink = jest.fn();
  3. drinkEach(drink, ['lemon', 'octopus']);
  4. expect(drink).toHaveBeenCalledTimes(2);
  5. });

.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:

  1. test('registration applies correctly to orange La Croix', () => {
  2. const beverage = new LaCroix('orange');
  3. register(beverage);
  4. const f = jest.fn();
  5. applyToAll(f);
  6. expect(f).toHaveBeenCalledWith(beverage);
  7. });

.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:

  1. test('applying to all flavors does mango last', () => {
  2. const drink = jest.fn();
  3. applyToAllFlavors(drink);
  4. expect(drink).toHaveBeenLastCalledWith('mango');
  5. });

.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:

  1. test('drinkEach drinks each drink', () => {
  2. const drink = jest.fn();
  3. drinkEach(drink, ['lemon', 'octopus']);
  4. expect(drink).toHaveBeenNthCalledWith(1, 'lemon');
  5. expect(drink).toHaveBeenNthCalledWith(2, 'octopus');
  6. });
note" class="reference-link">预期 - 图5note

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:

  1. test('drinks returns', () => {
  2. const drink = jest.fn(() => true);
  3. drink();
  4. expect(drink).toHaveReturned();
  5. });

.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:

  1. test('drink returns twice', () => {
  2. const drink = jest.fn(() => true);
  3. drink();
  4. drink();
  5. expect(drink).toHaveReturnedTimes(2);
  6. });

.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:

  1. test('drink returns La Croix', () => {
  2. const beverage = {name: 'La Croix'};
  3. const drink = jest.fn(beverage => beverage.name);
  4. drink(beverage);
  5. expect(drink).toHaveReturnedWith('La Croix');
  6. });

.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:

  1. test('drink returns La Croix (Orange) last', () => {
  2. const beverage1 = {name: 'La Croix (Lemon)'};
  3. const beverage2 = {name: 'La Croix (Orange)'};
  4. const drink = jest.fn(beverage => beverage.name);
  5. drink(beverage1);
  6. drink(beverage2);
  7. expect(drink).toHaveLastReturnedWith('La Croix (Orange)');
  8. });

.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:

  1. test('drink returns expected nth calls', () => {
  2. const beverage1 = {name: 'La Croix (Lemon)'};
  3. const beverage2 = {name: 'La Croix (Orange)'};
  4. const drink = jest.fn(beverage => beverage.name);
  5. drink(beverage1);
  6. drink(beverage2);
  7. expect(drink).toHaveNthReturnedWith(1, 'La Croix (Lemon)');
  8. expect(drink).toHaveNthReturnedWith(2, 'La Croix (Orange)');
  9. });
note" class="reference-link">预期 - 图6note

The nth argument must be positive integer starting from 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.

  1. expect([1, 2, 3]).toHaveLength(3);
  2. expect('abc').toHaveLength(3);
  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.

  1. // Object containing house features to be tested
  2. const houseForSale = {
  3. bath: true,
  4. bedrooms: 4,
  5. kitchen: {
  6. amenities: ['oven', 'stove', 'washer'],
  7. area: 20,
  8. wallColor: 'white',
  9. 'nice.oven': true,
  10. },
  11. livingroom: {
  12. amenities: [
  13. {
  14. couch: [
  15. ['large', {dimensions: [20, 20]}],
  16. ['small', {dimensions: [10, 10]}],
  17. ],
  18. },
  19. ],
  20. },
  21. 'ceiling.height': 2,
  22. };
  23. test('this house has my desired features', () => {
  24. // Example Referencing
  25. expect(houseForSale).toHaveProperty('bath');
  26. expect(houseForSale).toHaveProperty('bedrooms', 4);
  27. expect(houseForSale).not.toHaveProperty('pool');
  28. // Deep referencing using dot notation
  29. expect(houseForSale).toHaveProperty('kitchen.area', 20);
  30. expect(houseForSale).toHaveProperty('kitchen.amenities', [
  31. 'oven',
  32. 'stove',
  33. 'washer',
  34. ]);
  35. expect(houseForSale).not.toHaveProperty('kitchen.open');
  36. // Deep referencing using an array containing the keyPath
  37. expect(houseForSale).toHaveProperty(['kitchen', 'area'], 20);
  38. expect(houseForSale).toHaveProperty(
  39. ['kitchen', 'amenities'],
  40. ['oven', 'stove', 'washer'],
  41. );
  42. expect(houseForSale).toHaveProperty(['kitchen', 'amenities', 0], 'oven');
  43. expect(houseForSale).toHaveProperty(
  44. 'livingroom.amenities[0].couch[0][1].dimensions[0]',
  45. 20,
  46. );
  47. expect(houseForSale).toHaveProperty(['kitchen', 'nice.oven']);
  48. expect(houseForSale).not.toHaveProperty(['kitchen', 'open']);
  49. // Referencing keys with dot in the key itself
  50. expect(houseForSale).toHaveProperty(['ceiling.height'], 'tall');
  51. });

.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:

  1. test('adding works sanely with decimals', () => {
  2. expect(0.2 + 0.1).toBe(0.3); // Fails!
  3. });
  4. });

It fails because in JavaScript, 0.2 + 0.1 is actually 0.30000000000000004.

For example, this test passes with a precision of 5 digits:

  1. test('adding works sanely with decimals', () => {
  2. expect(0.2 + 0.1).toBeCloseTo(0.3, 5);
  3. });

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:

  1. test('there is a new flavor idea', () => {
  2. expect(fetchNewFlavorIdea()).toBeDefined();
  3. });

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:

  1. drinkSomeLaCroix();
  2. if (!getErrors()) {
  3. drinkMoreLaCroix();
  4. }

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:

  1. test('drinking La Croix does not lead to errors', () => {
  2. drinkSomeLaCroix();
  3. expect(getErrors()).toBeFalsy();
  4. });

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:

  1. test('ounces per can is more than 10', () => {
  2. expect(ouncesPerCan()).toBeGreaterThan(10);
  3. });

.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:

  1. test('ounces per can is at least 12', () => {
  2. expect(ouncesPerCan()).toBeGreaterThanOrEqual(12);
  3. });

.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:

  1. test('ounces per can is less than 20', () => {
  2. expect(ouncesPerCan()).toBeLessThan(20);
  3. });

.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:

  1. test('ounces per can is at most 12', () => {
  2. expect(ouncesPerCan()).toBeLessThanOrEqual(12);
  3. });

.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.

  1. class A {}
  2. expect(new A()).toBeInstanceOf(A);
  3. expect(() => {}).toBeInstanceOf(Function);
  4. 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.

  1. function bloop() {
  2. return null;
  3. }
  4. test('bloop returns null', () => {
  5. expect(bloop()).toBeNull();
  6. });

.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:

  1. drinkSomeLaCroix();
  2. if (thirstInfo()) {
  3. drinkMoreLaCroix();
  4. }

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:

  1. test('drinking La Croix leads to having thirst info', () => {
  2. drinkSomeLaCroix();
  3. expect(thirstInfo()).toBeTruthy();
  4. });

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:

  1. test('the best drink for octopus flavor is undefined', () => {
  2. expect(bestDrinkForFlavor('octopus')).toBeUndefined();
  3. });

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.

  1. test('passes when value is NaN', () => {
  2. expect(NaN).toBeNaN();
  3. expect(1).not.toBeNaN();
  4. });

.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:

  1. test('the flavor list contains lime', () => {
  2. expect(getAllFlavors()).toContain('lime');
  3. });

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.

  1. describe('my beverage', () => {
  2. test('is delicious and not sour', () => {
  3. const myBeverage = {delicious: true, sour: false};
  4. expect(myBeverages()).toContainEqual(myBeverage);
  5. });
  6. });

.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:

  1. const can1 = {
  2. flavor: 'grapefruit',
  3. ounces: 12,
  4. };
  5. const can2 = {
  6. flavor: 'grapefruit',
  7. ounces: 12,
  8. };
  9. describe('the La Croix cans on my desk', () => {
  10. test('have all the same properties', () => {
  11. expect(can1).toEqual(can2);
  12. });
  13. test('are not the exact same can', () => {
  14. expect(can1).not.toBe(can2);
  15. });
  16. });
tip

.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) as expect(received.equals(expected)).toBe(true)
  • rewrite expect(received).not.toEqual(expected) as expect(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:

  1. describe('an essay on the best flavor', () => {
  2. test('mentions grapefruit', () => {
  3. expect(essayOnTheBestFlavor()).toMatch(/grapefruit/);
  4. expect(essayOnTheBestFlavor()).toMatch(new RegExp('grapefruit'));
  5. });
  6. });

This matcher also accepts a string, which it will try to match:

  1. describe('grapefruits are healthy', () => {
  2. test('grapefruits are a fruit', () => {
  3. expect('grapefruits').toMatch('fruit');
  4. });
  5. });

.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.

  1. const houseForSale = {
  2. bath: true,
  3. bedrooms: 4,
  4. kitchen: {
  5. amenities: ['oven', 'stove', 'washer'],
  6. area: 20,
  7. wallColor: 'white',
  8. },
  9. };
  10. const desiredHouse = {
  11. bath: true,
  12. kitchen: {
  13. amenities: ['oven', 'stove', 'washer'],
  14. wallColor: expect.stringMatching(/white|yellow/),
  15. },
  16. };
  17. test('the house has my desired features', () => {
  18. expect(houseForSale).toMatchObject(desiredHouse);
  19. });
  1. describe('toMatchObject applied to arrays', () => {
  2. test('the number of elements must match exactly', () => {
  3. expect([{foo: 'bar'}, {baz: 1}]).toMatchObject([{foo: 'bar'}, {baz: 1}]);
  4. });
  5. test('.toMatchObject is called for each elements, so extra object properties are okay', () => {
  6. expect([{foo: 'bar'}, {baz: 1, extra: 'quux'}]).toMatchObject([
  7. {foo: 'bar'},
  8. {baz: 1},
  9. ]);
  10. });
  11. });

.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 types as well as structure.

Differences from .toEqual:

  • Keys with undefined properties are checked. Keys with undefined properties are checked. e.g. {a: undefined, b: 2} does not match {b: 2} when using .toStrictEqual.
  • Array sparseness is checked. Array sparseness is checked. e.g. [, 1] does not match [undefined, 1] when using .toStrictEqual.
  • Object types are checked to be equal. Object types are checked to be equal. e.g. A class instance with fields a and b will not equal a literal object with fields a and b.
  1. class LaCroix {
  2. constructor(flavor) {
  3. this.flavor = flavor;
  4. }
  5. }
  6. describe('the La Croix cans on my desk', () => {
  7. test('are not semantically the same', () => {
  8. expect(new LaCroix('lemon')).toEqual({flavor: 'lemon'});
  9. expect(new LaCroix('lemon')).not.toStrictEqual({flavor: 'lemon'});
  10. });
  11. });

.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:

  1. test('throws on octopus', () => {
  2. expect(() => {
  3. drinkFlavor('octopus');
  4. }).toThrow();
  5. });
tip

You must wrap the code in a function, otherwise the error will not be caught and the assertion will fail.

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:

  1. function drinkFlavor(flavor) {
  2. if (flavor == 'octopus') {
  3. throw new DisgustingFlavorError('yuck, octopus flavor');
  4. }
  5. // Do some other stuff
  6. }

We could test this error gets thrown in several ways:

  1. test('throws on octopus', () => {
  2. function drinkOctopus() {
  3. drinkFlavor('octopus');
  4. }
  5. // Test that the error message says "yuck" somewhere: these are equivalent
  6. expect(drinkOctopus).toThrowError(/yuck/);
  7. expect(drinkOctopus).toThrowError('yuck');
  8. // Test the exact error message
  9. expect(drinkOctopus).toThrowError(/^yuck, octopus flavor$/);
  10. expect(drinkOctopus).toThrowError(new Error('yuck, octopus flavor'));
  11. // Test that we get a DisgustingFlavorError
  12. expect(drinkOctopus).toThrowError(DisgustingFlavorError);
  13. });

.toThrowErrorMatchingSnapshot(hint?)

Use .toThrowErrorMatchingSnapshot to test that a function throws an error matching the most recent snapshot when it is called.

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.

For example, let’s say you have a drinkFlavor function that throws whenever the flavor is 'octopus', and is coded like this:

  1. function drinkFlavor(flavor) {
  2. if (flavor == 'octopus') {
  3. throw new DisgustingFlavorError('yuck, octopus flavor');
  4. }
  5. // Do some other stuff
  6. }

The test for this function will look this way:

  1. test('throws on octopus', () => {
  2. function drinkOctopus() {
  3. drinkFlavor('octopus');
  4. }
  5. expect(drinkOctopus).toThrowErrorMatchingSnapshot();
  6. });

And it will generate the following snapshot:

  1. exports[`drinking flavors throws on octopus 1`] = `"yuck, octopus flavor"`;

Check out React Tree Snapshot Testing for more information on snapshot testing.

.toThrowErrorMatchingInlineSnapshot(inlineSnapshot)

Use .toThrowErrorMatchingInlineSnapshot to test that a function throws an error matching the most recent snapshot when it is called.

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.