预计·续4

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)');});

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

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 testedconst houseForSale = {  bath: true,  bedrooms: 4,  kitchen: {    amenities: ['oven', 'stove', 'washer'],    area: 20,    wallColor: 'white',    'nice.oven': true,  },  '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(['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: