Skip to main content
Version: 25.x

Aşteptări

When you're writing tests, you often need to check that values meet certain conditions. expect gives you access to a number of "matchers" that let you validate different things.

tip

For additional Jest matchers maintained by the Jest Community check out jest-extended.

Metode


Reference

expect(value)

Funcţia expect este folosită de fiecare dată când vrei să testezi o valoare. Foarte rar vei apela expect de una singură. În schimb, vei folosi expect împreună cu funcție de "comparare" pentru a pretinde ceva despre o valoare.

Este mai uşor de înţeles acest lucru printr-un exemplu. Să presupunem că aveţi o metodă bestLaCroixFlavor() care ar trebui să returneze 'grapefruit'. Iată cum ai testa acest lucru:

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

In this case, toBe is the matcher function. There are a lot of different matcher functions, documented below, to help you test different things.

Argumentul funcției expect trebuie să fie valoarea care produce codul şi orice argument pentru funcția comparator ar trebui să fie valoarea corectă. Dacă le amestecați, testele vor funcţiona în continuare, dar mesajele de eroare pentru testele eșuate vor arăta ciudat.

expect.extend(matchers)

Utilizaţi expect.extend pentru a adăuga proprii comparatorii. For example, let's say that you're testing a number utility library and you're frequently asserting that numbers appear within particular ranges of other numbers. You could abstract that into a toBeWithinRange matcher:

expect.extend({
toBeWithinRange(received, floor, ceiling) {
const pass = received >= floor && received <= ceiling;
if (pass) {
return {
message: () =>
`expected ${received} not to be within range ${floor} - ${ceiling}`,
pass: true,
};
} else {
return {
message: () =>
`expected ${received} to be within range ${floor} - ${ceiling}`,
pass: false,
};
}
},
});

test('numeric ranges', () => {
expect(100).toBeWithinRange(90, 110);
expect(101).not.toBeWithinRange(0, 100);
expect({apples: 6, bananas: 3}).toEqual({
apples: expect.toBeWithinRange(1, 10),
bananas: expect.not.toBeWithinRange(11, 20),
});
});
info

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

expect.extend({
toBeWithinRange(received, floor, ceiling) {
// ...
},
});

interface CustomMatchers<R = unknown> {
toBeWithinRange(floor: number, ceiling: number): R;
}

declare global {
namespace jest {
interface Expect extends CustomMatchers {}
interface Matchers<R> extends CustomMatchers<R> {}
interface InverseAsymmetricMatchers extends CustomMatchers {}
}
}

If you want to move the typings to a separate file (e.g. types/jest/index.d.ts), you may need to an export, e.g.:

declare global {
namespace jest {
interface Matchers<R> {
toBeWithinRange(a: number, b: number): R;
}
}
}
export {};

Async Matchers

expect.extend also supports async matchers. Async matchers return a Promise so you will need to await the returned value. Let's use an example matcher to illustrate the usage of them. We are going to implement a matcher called toBeDivisibleByExternalValue, where the divisible number is going to be pulled from an external source.

expect.extend({
async toBeDivisibleByExternalValue(received) {
const externalValue = await getExternalValueFromRemoteSource();
const pass = received % externalValue == 0;
if (pass) {
return {
message: () =>
`expected ${received} not to be divisible by ${externalValue}`,
pass: true,
};
} else {
return {
message: () =>
`expected ${received} to be divisible by ${externalValue}`,
pass: false,
};
}
},
});

test('is divisible by external value', async () => {
await expect(100).toBeDivisibleByExternalValue();
await expect(101).not.toBeDivisibleByExternalValue();
});

Custom Matchers API

Matchers should return an object (or a Promise of an object) with two keys. pass indică dacă a fost o potrivire sau nu, şi message oferă o funcţie fără argumente care returnează un mesaj de eroare în caz de eşec. Astfel, atunci când pass este fals, message trebuie să returneze mesajul de eroare pentru atunci când expect(x).yourMatcher() eșuează. Iar când pass este adevărat, message trebuie să returneze mesajul de eroare pentru atunci când expect(x).not.yourMatcher() eșuează.

Matchers are called with the argument passed to expect(x) followed by the arguments passed to .yourMatcher(y, z):

expect.extend({
yourMatcher(x, y, z) {
return {
pass: true,
message: () => '',
};
},
});

These helper functions and properties can be found on this inside a custom matcher:

this.isNot

A boolean to let you know this matcher was called with the negated .not modifier allowing you to display a clear and correct matcher hint (see example code).

this.promise

A string allowing you to display a clear and correct matcher hint:

  • 'rejects' if matcher was called with the promise .rejects modifier
  • 'resolves' if matcher was called with the promise .resolves modifier
  • '' if matcher was not called with a promise modifier

this.equals(a, b)

Aceasta este o funcţie de egalitate-în-adâncime, care va returna true dacă două obiecte au aceleaşi valori (recursiv).

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.

Cele mai utile sunt matcherHint, printExpected şi printReceived pentru a formata frumos mesajele de eroare. De exemplu, să aruncăm o privire asupra implementării pentru toBe:

const diff = require('jest-diff');
expect.extend({
toBe(received, expected) {
const options = {
comment: 'Object.is equality',
isNot: this.isNot,
promise: this.promise,
};

const pass = Object.is(received, expected);

const message = pass
? () =>
// eslint-disable-next-line prefer-template
this.utils.matcherHint('toBe', undefined, undefined, options) +
'\n\n' +
`Expected: not ${this.utils.printExpected(expected)}\n` +
`Received: ${this.utils.printReceived(received)}`
: () => {
const diffString = diff(expected, received, {
expand: this.expand,
});
return (
// eslint-disable-next-line prefer-template
this.utils.matcherHint('toBe', undefined, undefined, options) +
'\n\n' +
(diffString && diffString.includes('- Expect')
? `Difference:\n\n${diffString}`
: `Expected: ${this.utils.printExpected(expected)}\n` +
`Received: ${this.utils.printReceived(received)}`)
);
};

return {actual: received, message, pass};
},
});

Acest lucru va afișa ceva similar:

  expect(received).toBe(expected)

Expected value to be (using Object.is):
"banana"
Received:
"apple"

Atunci când o aserţiune eșuează, mesajul de eroare ar trebui să dea detalii suficiente pentru utilizator, astfel încât ei poată rezolva problema rapid. Ar trebui să construiți mesaje de eroare precise pentru a vă asigura că utilizatorii de aserțiunilor voastre au o experienţă bună.

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. 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() validează orice, mai putin null sau undefined. Îl puteţi folosi în interiorul lui toEqual sau toBeCalledWith în locul unei valori concrete. De exemplu, dacă doriţi să verificaţi că o dublură a fost apelată cu un argument non-null:

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

expect.any(constructor)

expect.any(constructor) matches anything that was created with the given constructor or if it's a primitive that is of the passed type. Îl puteţi folosi în interiorul lui toEqual sau toBeCalledWith în locul unei valori concrete. De exemplu, dacă doriţi să verificaţi că o dublură a fost apelată cu un număr:

class Cat {}
function getCat(fn) {
return fn(new Cat());
}

test('randocall calls its callback with a class instance', () => {
const mock = jest.fn();
getCat(mock);
expect(mock).toHaveBeenCalledWith(expect.any(Cat));
});

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).toHaveBeenCalledWith(expect.any(Number));
});

expect.arrayContaining(array)

expect.arrayContaining(array) validează o listă care conţine toate elementele din lista pasată. 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.

Îl puteţi folosi în locul unei valori concrete:

  • 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! 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) verifică dacă un anumit număr de aserțiuni au fost apelate în timpul unui test. Acest lucru este adesea util când testăm cod asincron, pentru a ne asigura că aserțiunile dintr-un callback chiar sunt apelate.

De exemplu, să presupunem că avem o funcţie doAsync care primeşte două callback-uri callback1 şi callback2, care vor fi apelate asincron într-o ordine necunoscută. Putem testa acest lucru în felul următor:

test('doAsync calls both callbacks', () => {
expect.assertions(2);
function callback1(data) {
expect(data).toBeTruthy();
}
function callback2(data) {
expect(data).toBeTruthy();
}

doAsync(callback1, callback2);
});

Apelul expect.assertions(2) asigură că ambele callback-uri au fost apelate.

expect.hasAssertions()

expect.hasAssertions() verifică dacă cel puțin o aserțiune a fost apelată în timpul unui test. Acest lucru este adesea util când testăm cod asincron, pentru a ne asigura că aserțiunile dintr-un callback chiar sunt apelate.

De exemplu, să spunem că avem câteva funcţii care se ocupă toate de stare. prepareState apelează un callback cu un obiect de stare, validateState ruleaza pe acel obiect de stare şi waitOnState returnează o promisiune care aşteaptă până când toate callback-urile prepareState se termină. Putem testa acest lucru în felul următor:

test('prepareState prepares a valid state', () => {
expect.hasAssertions();
prepareState(state => {
expect(validateState(state)).toBeTruthy();
});
return waitOnState();
});

Apelul expect.hasAssertions() ne asigură că prepareState este apelat.

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.

It is the inverse of expect.arrayContaining.

describe('not.arrayContaining', () => {
const expected = ['Samantha'];

it('matches if the actual array does not contain the expected elements', () => {
expect(['Alice', 'Bob', 'Eve']).toEqual(
expect.not.arrayContaining(expected),
);
});
});

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. Prin urmare, validează un obiect primit care conţine proprietăți care nu fac parte din obiectul aşteptat.

It is the inverse of expect.objectContaining.

describe('not.objectContaining', () => {
const expected = {foo: 'bar'};

it('matches if the actual object does not contain expected key: value pairs', () => {
expect({bar: 'baz'}).toEqual(expect.not.objectContaining(expected));
});
});

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.

describe('not.stringContaining', () => {
const expected = 'Hello world!';

it('matches if the received value does not contain the expected substring', () => {
expect('How are you?').toEqual(expect.not.stringContaining(expected));
});
});

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.

describe('not.stringMatching', () => {
const expected = /Hello world!/;

it('matches if the received value does not match the expected regex', () => {
expect('How are you?').toEqual(expect.not.stringMatching(expected));
});
});

expect.objectContaining(object)

expect.objectContaining(object) validează orice obiect primit care conține în mod recursiv proprietăţile aşteptate. Adică, obiectul asteptat este un subset al obiectului primit. Therefore, it matches a received object which contains properties that are present in the expected object.

În loc de valori literale în obiectul aşteptat, puteţi utiliza validatori, expect.anything(), şi aşa mai departe.

De exemplu, să presupunem că ne aşteptăm ca o funcţie onPress să fie apelată cu un obiect de tip Event, şi tot ce avem nevoie să verificăm este că evenimentul are proprietățile event.x și event.y. Putem testa acest lucru în felul următor:

test('onPress gets called with the right thing', () => {
const onPress = jest.fn();
simulatePresses(onPress);
expect(onPress).toHaveBeenCalledWith(
expect.objectContaining({
x: expect.any(Number),
y: expect.any(Number),
}),
);
});

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.

Îl puteţi folosi în locul unei valori concrete:

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

Acest exemplu arată cum puteţi imbrica mai mulți validatori asimetrici, cu expect.stringMatching în interiorul unui expect.arrayContaining.

describe('stringMatching in arrayContaining', () => {
const expected = [
expect.stringMatching(/^Alic/),
expect.stringMatching(/^[BR]ob/),
];
it('matches even if received contains additional elements', () => {
expect(['Alicia', 'Roberto', 'Evelina']).toEqual(
expect.arrayContaining(expected),
);
});
it('does not match if received does not contain expected elements', () => {
expect(['Roberto', 'Evelina']).not.toEqual(
expect.arrayContaining(expected),
);
});
});

expect.addSnapshotSerializer(serializer)

Puteţi apela expect.addSnapshotSerializer pentru a adăuga un modul care formatează structuri de date specifice aplicaţiei.

Pentru un fişier de individual test, un modul suplimentar precede orice module din configurarea snapshotSerializers, care precedă la rândul lor serializatoarele implicite pentru tipurile JavaScript şi elemente React. Ultimul modul adăugat este primul testat.

import serializer from 'my-serializer-module';
expect.addSnapshotSerializer(serializer);

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

A se vedea configurarea Jest pentru mai multe informaţii.

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

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.

De exemplu, acest cod testează că promisiunea se rezolvă şi că valoarea rezultată este 'lemon':

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

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.

Alternativ, puteţi utiliza async/await în combinaţie cu .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.

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

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.

De exemplu, acest cod va valida unele proprietăţi ale obiectului can:

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. De exemplu, din cauza rotunjirilor, în JavaScript 0.2 + 0.1 nu este strict egal cu 0.3. Dacă aveţi numerele cu virgulă mobilă, încercaţi .toBeCloseTo în schimb.

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:

  • 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()

Există și cu aliasul: .toBeCalled()

Utilizaţi .toHaveBeenCalledWith pentru a vă asigura că o funcţie mock a fost apelată cu niște argumente specifice. 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. 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? Se poate face asta cu următorul test:

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)

Utilizaţi . toHaveBeenCalledTimes pentru a vă asigura că o funcţie mock a fost apelată de un anumit număr de ori.

De exemplu, să presupunem că avem o funcţie drinkEach(drink, Array<flavor>), care primește o funcţie drink pe care o aplică tuturor băuturilor primite. Aţi putea verifica faptul că funcţia a fost apelată de un număr exact de ori. Se poate face asta cu următorul test:

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

.toHaveBeenCalledWith(arg1, arg2, ...)

Există și cu aliasul: .toBeCalledWith()

Utilizaţi .toHaveBeenCalledWith pentru a vă asigura că o funcţie mock a fost apelată cu niște argumente specifice. The arguments are checked with the same algorithm that .toEqual uses.

De exemplu, să spunem că puteţi înregistra o băutură cu funcție register, şi applyToAll(f) ar trebui să aplice funcția f tuturor băuturilor înregistrate. Pentru a vă asigura că aceasta funcţionează, ați putea scrie:

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

Există și cu aliasul: .lastCalledWith(arg1, arg2, ...)

Dacă aveţi o funcţie mock, puteţi utiliza .toHaveBeenLastCalledWith pentru a testa cu ce argumente a fost apelată ultima dată. De exemplu, să presupunem că aveţi o funcţie applyToAllFlavors(f), care aplică f la o grămadă de arome, şi doriţi să vă asiguraţi că, atunci când o apelați, ultima aromă cu care operează este 'mango'. Puteţi scrie:

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'. Puteţi scrie:

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. Puteţi scrie:

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.

For example, let's say you have a mock drink that returns true. Puteţi scrie:

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. Puteţi scrie:

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. 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. Puteţi scrie:

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. 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. Puteţi scrie:

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)

Utilizaţi .toHaveLength pentru a verifica dacă un obiect are o proprietate de .length şi are o anumită valoare numerică.

Acest lucru este util mai ales pentru a verifica dimensiunea listelor sau a șirurilor de caractere.

expect([1, 2, 3]).toHaveLength(3);
expect('abc').toHaveLength(3);
expect('').not.toHaveLength(5);

.toHaveProperty(keyPath, value?)

Utilizaţi .toHaveProperty pentru a verifica dacă există o anumită proprietate la referinţa keyPath pentru un obiect. 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).

Exemplul următor conţine un obiect houseForSale cu proprietăţi imbricate. 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,
},
'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. 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:

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

Utilizaţi .toBeDefined pentru a verifica dacă o variabilă nu este nedefinită. 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();
});

Ați putea scrie și expect(fetchNewFlavorIdea()).not.toBe(undefined), dar este de preferat să evitați referința la undefined în mod direct în codul vostru.

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

drinkSomeLaCroix();
if (!getErrors()) {
drinkMoreLaCroix();
}

Nu ar trebui sa ne pese ce anume returnează getErrors, specific - ar putea returna false, null, sau 0, codul funcționând identic. Așadar, dacă doriţi să testaţi ca nu există erori după ce ați băut niște La Croix, ați putea scrie:

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.

.toBeGreaterThan(number | bigint)

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:

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

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.

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.

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:

drinkSomeLaCroix();
if (thirstInfo()) {
drinkMoreLaCroix();
}

Nu ar trebui sa ne pese ce anume returnează thirstInfo, specific - ar putea returna fie true fie un obiect complex, codul funcționând identic. 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.

.toBeUndefined()

Utilizaţi .toBeUndefined pentru a verifica dacă o variabilă este nedefinită. De exemplu, dacă doriţi să verificaţi dacă o funcţie bestDrinkForFlavor(flavor) returnează undefined pentru aroma 'octopus':

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

Ați putea scrie și expect(bestDrinkForFlavor()).toBe(undefined), dar este de preferat să evitați referința la undefined în mod direct în codul vostru.

.toBeNaN()

Use .toBeNaN when checking a value is NaN.

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

.toContain(item)

Utilizaţi .toContain atunci când doriţi să verificați dacă un element se află într-o listă. Pentru testarea elementele din matrice, foloseste ===, o verificare de strictă egalitate. .toContain poate de asemenea verifica dacă un string este un subșir al unui alt şir.

De exemplu, dacă getAllFlavors() returnează o listă de arome şi doriţi să vă asiguraţi că lime se află în ea, se poate scrie:

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)

Utilizaţi .toContainEqual atunci când doriţi pentru să verificați dacă un element cu o anumită structură şi valori este conţinut într-o listă. Pentru testarea elementele din listă, acest validator verifică recursiv egalitatea tuturor proprietăților, în loc să verifice referința obiectului.

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.

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

toEqual ignores object keys with undefined properties, undefined array items, array sparseness, or object type mismatch. To take these into account use .toStrictEqual instead.

info

.toEqual won't perform a deep equality check for two errors. Numai proprietatea message al obiectului Error este luată în considerare pentru verificare. Este recomandat să utilizaţi .toThrow pentru testarea erorilor.

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:

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

Utilizaţi .toMatch pentru a verifica dacă un şir de caractere validează o expresie regulată.

De exemplu, s-ar putea să nu ştiţi exact ce returnează essayOnTheBestFlavor(), dar știți că este un şir foarte lung şi că ar trebui să conțină un subșir grapefruit. Puteți testa acest lucru în felul următor:

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

Acest validator acceptă, de asemenea, un şir de caractere, pe care va încerca să-l găsească:

describe('grapefruits are healthy', () => {
test('grapefruits are a fruit', () => {
expect('grapefruits').toMatch('fruit');
});
});

.toMatchObject(object)

Utilizaţi .toMatchObject pentru a verifica dacă un obiect JavaScript conține un subset de proprietăți ale altui obiect. Validează un obiecte care conţin proprietăți care nu fac parte din obiectul aşteptat.

Se poate pasa, de asemenea, o listă de obiecte, iar în cazul acesta metoda va returna adevărat numai în cazul în care fiecare obiect din lista primită se potrivește (în sensul toMatchObject descris mai sus) cu obiectul corespunzător din lista aşteptată. Acest lucru este util dacă doriţi să verificaţi că două liste se potrivesc in raport cu numărul lor de elemente, spre deosebire de arrayContaining, care permite elemente suplimentare în lista primită.

Aveţi posibilitatea să validați proprietăţi cu valori sau cu alți validatori.

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

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.

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

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 and b will not equal a literal object with fields a and b.
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?)

Utilizaţi .toThrow pentru a testa dacă o funcţie aruncă o excepție atunci când este apelată. De exemplu, dacă vrem să testăm că drinkFlavor('octopus') aruncă o excepție, vom scrie:

test('throws on octopus', () => {
expect(() => {
drinkFlavor('octopus');
}).toThrow();
});
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

De exemplu, să presupunem că drinkFlavor este implementată în felul următor:

function drinkFlavor(flavor) {
if (flavor == 'octopus') {
throw new DisgustingFlavorError('yuck, octopus flavor');
}
// Do some other stuff
}

Am putea testa în mai multe moduri că această eroare este aruncată:

test('throws on octopus', () => {
function drinkOctopus() {
drinkFlavor('octopus');
}

// Test that the error message says "yuck" somewhere: these are equivalent
expect(drinkOctopus).toThrow(/yuck/);
expect(drinkOctopus).toThrow('yuck');

// Test the exact error message
expect(drinkOctopus).toThrow(/^yuck, octopus flavor$/);
expect(drinkOctopus).toThrow(new Error('yuck, octopus flavor'));

// Test that we get a DisgustingFlavorError
expect(drinkOctopus).toThrow(DisgustingFlavorError);
});

.toThrowErrorMatchingSnapshot(hint?)

Utilizaţi .toThrowErrorMatchingSnapshot pentru a testa dacă o funcţie aruncă o eroare în timpul comparării cu cea mai recentă imagine, atunci când este apelată.

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.

De exemplu, să presupunem că aveţi o funcţie drinkFlavor care aruncă o excepție ori de câte ori aroma este 'octopus', şi este implementată în felul următor:

function drinkFlavor(flavor) {
if (flavor == 'octopus') {
throw new DisgustingFlavorError('yuck, octopus flavor');
}
// Do some other stuff
}

Testul pentru această funcţie va arăta astfel:

test('throws on octopus', () => {
function drinkOctopus() {
drinkFlavor('octopus');
}

expect(drinkOctopus).toThrowErrorMatchingSnapshot();
});

Care va genera următoarea imagine:

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.