Skip to main content
Versão: 29.7

Expect

Quando você está escrevendo testes, geralmente precisa verificar se os valores atendem a certas condições. expect lhe dá acesso a inúmeros "matchers" que permitem validar diferentes coisas.

tip

Outros "matchers" mantidos pela Comunidade Jest podem ser encontrados em jest-extended.

informação

Os exemplos de TypeScript desta página só funcionarão como documentados se você importar explicitamente APIs do Jest:

import {expect, jest, test} from '@jest/globals';

Consulte o guia Iniciando para obter detalhes sobre como configurar Jest com TypeScript.

Referência


Expect

expect(value)

A função expect é usada toda vez que você quer testar um valor. Você raramente irá usar o expect sozinho. Em vez disso, você irá usar expect junto com uma função "matcher" para verificar algo sobre um valor.

É mais fácil de entender isto com um exemplo. Digamos que você tenha um método bestLaCroixFlavor() que se espera retornar a string 'grapefruit'. Veja como você testaria isso:

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

Neste caso, toBe é a função "matcher". Existem muitas funções "matcher" diferentes, documentadas abaixo, para ajuda-lo a testar coisas diferentes.

O argumento para expect deve ser o valor que o seu código produz, e qualquer argumento para o matcher deve ser o valor correto esperado. Se você misturá-los, os testes ainda irão funcionar, mas as mensagens de erro em testes que falharem vão parecer estranhas.

Modifiers

.not

Se você sabe como testar algo, .not permite que você teste seu oposto. Por exemplo, este código testa que o melhor sabor da La Croix não é "coconut":

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

.resolves

Use resolves para decodificar o valor de uma promessa cumprida, para que qualquer outro matcher possa então ser encadeado. Se a promessa for rejeitada a verificação falhará.

Por exemplo, este código de testes que a promessa resolve e que o valor resultante é '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.

Como alternativa, você pode usar async/await em combinação com .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 para decodificar o motivo de uma promessa rejeitada, para que qualquer outro matcher possa ser encadeado. Se a promessa é cumprida a verificação falhará.

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

Matchers

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

Por exemplo, este código irá validar algumas propriedades do objeto 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. Por exemplo, devido a arredondamentos, em JavaScript 0.2 + 0.1 não é estritamente igual a 0.3. Se você tem números de ponto flutuante, tente usar de preferência .toBeCloseTo.

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

Também sob o pseudônimo: .toBeCalled()

Use .toHaveBeenCalled to ensure that a mock function was called.

For example, let's say you have a drinkAll(drink, flavour) function that takes a drink function and applies it to all available beverages. 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? Você pode fazer isso com este conjunto de testes:

function drinkAll(callback, flavour) {
if (flavour !== 'octopus') {
callback(flavour);
}
}

describe('drinkAll', () => {
test('drinks something lemon-flavoured', () => {
const drink = jest.fn();
drinkAll(drink, 'lemon');
expect(drink).toHaveBeenCalled();
});

test('does not drink something octopus-flavoured', () => {
const drink = jest.fn();
drinkAll(drink, 'octopus');
expect(drink).not.toHaveBeenCalled();
});
});

.toHaveBeenCalledTimes(number)

Also under the alias: .toBeCalledTimes(number)

Use .toHaveBeenCalledTimes para garantir que uma função de simulação (mock, em inglês) foi chamada um número exato de vezes.

Por exemplo, vamos dizer você tem uma função drinkEach(drink, Array<flavor>) que usa uma função drink e aplica ela ao array das bebidas passadas. Você pode querer verificar que a função "drink" foi chamada um número exato de vezes. Você pode fazer isso com este conjunto de testes:

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

.toHaveBeenCalledWith(arg1, arg2, ...)

Também sob o pseudônimo: .toBeCalledWith()

Use .toHaveBeenCalledWith para garantir que uma função de simulação (mock, em inglês) foi chamada com argumentos específicos. The arguments are checked with the same algorithm that .toEqual uses.

Por exemplo, digamos que você pode registrar uma bebida com uma função register, e applyToAll(f) deve aplicar a função f para todas as bebidas registradas. Para garantir que isso funciona, você poderia escrever:

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

Também sob o pseudônimo: .lastCalledWith(arg1, arg2, ...)

Se você tiver uma função de simulação (mock, em inglês), você pode usar .toHaveBeenLastCalledWith para testar com quais argumentos foi chamada na última vez. Por exemplo, digamos que você tem uma função applyToAllFlavors(f) que aplica f para um monte de sabores, e você deseja garantir que quando você chamá-la, o último sabor em que ela opera é 'mango'. Você pode escrever:

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'. Você pode escrever:

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. Você pode escrever:

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. Você pode escrever:

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. Você pode escrever:

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. Você pode escrever:

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. Você pode escrever:

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 para verificar que um objeto tem uma propriedade .length e está definida para um determinado valor numérico.

Isto é especialmente útil para verificar arrays ou tamanho de strings.

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

.toHaveProperty(keyPath, value?)

Use .toHaveProperty para verificar se a propriedade fornecida na referência keyPath existe para um objeto. 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).

O exemplo a seguir contém um objeto houseForSale com propriedades aninhadas. 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,
},
livingroom: {
amenities: [
{
couch: [
['large', {dimensions: [20, 20]}],
['small', {dimensions: [10, 10]}],
],
},
],
},
'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(
'livingroom.amenities[0].couch[0][1].dimensions[0]',
20,
);
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()

Use .toBeDefined para verificar que uma variável não "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();
});

Você poderia escrever expect(fetchNewFlavorIdea()).not.toBe(undefined), mas é uma melhor prática evitar referência a undefined diretamente em seu código.

.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();
}

Você pode não se importar com o que getErrors retorna, especificamente - ele pode retornar false, null ou 0, e seu código ainda funcionaria. Então se você quiser testar que não existem erros depois de beber algumas La Croix, você poderia escrever:

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

Em JavaScript, existem seis valores "falsy" (que se traduzem em falso quando avaliados em um contexto booleano): false, 0, '', null, undefined e NaN. Todo o resto é "truthy" (se traduzem em verdadeiro quando avaliados em um contexto booleano).

.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) para verificar que um objeto é uma instância de uma classe. Este "matcher" usa instanceof por debaixo.

class A {}

expect(new A()).toBeInstanceOf(A);
expect(() => {}).toBeInstanceOf(Function);
expect(new A()).toBeInstanceOf(Function); // throws

.toBeNull()

.toBeNull() é o mesmo que .toBe(null), mas as mensagens de erro são um pouco mais agradáveis. Então use .toBeNull() quando você deseja verificar que algo é nulo.

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

Você pode não se importar o que thirstInfo retorna, especificamente - ele pode retornar true ou um objeto complexo, e seu código ainda funcionaria. 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();
});

Em JavaScript, existem seis valores "falsy" (que se traduzem em falso quando avaliados em um contexto booleano): false, 0, '', null, undefined e NaN. Todo o resto é "truthy" (se traduzem em verdadeiro quando avaliados em um contexto booleano).

.toBeUndefined()

Use .toBeUndefined para verificar se uma variável é "undefined". Por exemplo, se você quiser verificar que uma função bestDrinkForFlavor(flavor) retornará undefined para o sabor 'octopus', porque não há nenhuma boa bebida com sabor "octopus", ou polvo:

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

Você poderia escrever expect(bestDrinkForFlavor('octopus')).toBe(undefined), mas é uma melhor prática evitar se referir a undefined diretamente em seu código.

.toBeNaN()

Use .toBeNaN when checking a value is NaN.

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

.toContain(item)

Use .toContain quando você deseja verificar se um item está em um array. Para testar os itens no array, este usa ===, uma verificação de igualdade estrita. .toContain também pode verificar se uma string é uma substring de outra string.

Por exemplo, se getAllFlavors() retorna um array de sabores e você quer ter certeza que lime está lá, você pode escrever:

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)

Use .toContainEqual quando você deseja verificar que um item com uma estrutura específica e valores está contido em um array. Para testar os itens no array, este "matcher" recursivamente verifica a igualdade de todos os campos, em vez de verificar a identidade do objeto.

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 ignora as chaves de objeto com propriedas undefined, itens de array undefined, arrays dispersos ou incompatibilidade do tipo de objeto. To take these into account use .toStrictEqual instead.

informação

.toEqual won't perform a deep equality check for two errors. Apenas a propriedade message de um Error é considerada pela igualdade. É recomendável usar o "matcher" .toThrow para testes contra erros.

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)

Use .toMatch para verificar se uma string corresponde a uma expressão regular.

Por exemplo, você talvez não saiba o que exatamente essayOnTheBestFlavor() retorna, mas você sabe que é uma string muito longa, e a substring grapefruit deve estar em algum lugar. Você pode testar isso com:

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

Este "matcher" também aceita uma string, a qual tentará corresponder:

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

.toMatchObject(object)

Use .toMatchObject para verificar se um objeto JavaScript corresponde a um subconjunto das propriedades de um objeto. Combinará objetos recebidos com propriedades que não estão no objeto esperado.

Você também pode passar uma array de objetos, neste caso o método retornará verdadeiro somente se cada objeto na matriz recebida corresponder (no sentido toMatchObject descrito acima) o objeto correspondente no array esperado. Isso é útil se você deseja verificar que dois arrays correspondem em seu número de elementos, em oposição a arrayContaining, que permite elementos extras no array recebido.

Você pode corresponder propriedades contra valores ou "matchers".

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

Isso garante que um valor corresponda ao snapshot mais recente. Confira o guia de Teste de Snapshot para obter mais informações.

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

Use .toThrow para testar que uma função é capaz de lançar erros quando é chamada. Por exemplo, se queremos testar que drinkFlavor('octopus') lança um erro, porque o sabor "octopus", ou polvo, é muito nojento para beber, podemos escrever:

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

Por exemplo, digamos que drinkFlavor é codificado como segue:

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

Podemos fazer um teste se esse erro é lançado de diversas maneiras:

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

Use .toThrowErrorMatchingSnapshot para testar que uma função lança um erro que corresponde ao snapshot mais recente quando é chamada.

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.

Por exemplo, digamos que você tem uma função drinkFlavor que lança um erro sempre que o sabor é 'octopus', e é codificada como segue:

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

O teste para esta função ficará assim:

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

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

E irá gerar o seguinte snapshot:

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.

Asymmetric Matchers

expect.anything()

expect.anything() corresponde a qualquer coisa menos null ou undefined. You can use it inside toEqual or toHaveBeenCalledWith instead of a literal value. Por exemplo, se você quiser verificar que uma função de simulação (mock, em inglês) é chamada com um argumento não nulo:

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. You can use it inside toEqual or toHaveBeenCalledWith instead of a literal value. Por exemplo, se você quiser verificar que uma função de simulação (mock, em inglês) é chamada com um número:

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) corresponde a um array recebido que contém todos os elementos no array esperado. Ou seja, o array esperado é um subconjunto do array recebido. Portanto, combina com um array recebido que contém elementos que não estão no array esperado.

Você pode usá-lo em vez de um valor literal:

  • in toEqual or toHaveBeenCalledWith
  • 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.not.arrayContaining(array)

expect.not.arrayContaining(array) corresponde a um array recebido que não contém todos os elementos no array esperado. Ou seja, o array esperado não é um subconjunto do array recebido.

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

test('compare float in object properties', () => {
expect({
title: '0.1 + 0.2',
sum: 0.1 + 0.2,
}).toEqual({
title: '0.1 + 0.2',
sum: expect.closeTo(0.3, 5),
});
});

expect.objectContaining(object)

expect.objectContaining(object) corresponde a qualquer objeto recebido que recursivamente coincide com as propriedades esperadas. Ou seja, o objeto esperado é um subconjunto do objeto recebido. Therefore, it matches a received object which contains properties that are present in the expected object.

Em vez de valores literais de propriedade no objeto esperado, você pode usar "matchers", expect.anything(), e assim por diante.

Por exemplo, digamos que esperamos uma função onPress ser chamada com um objeto Event, e tudo que precisamos verificar é que o evento tem propriedades event.x e event.y. Podemos fazer isso com:

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.not.objectContaining(object)

expect.not.objectContaining(object) corresponde a qualquer objeto recebido que não corresponde recursivamente às propriedades esperadas. Ou seja, o objeto esperado não é um subconjunto do objeto recebido. Portanto, combina com um objeto recebido que contém propriedades que não estão no objeto esperado.

É a inversa de 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.stringContaining(string)

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

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.stringMatching(string | regexp)

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

Você pode usá-lo em vez de um valor literal:

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

Este exemplo também mostra como você pode aninhar vários "matchers" assimétricos, com expect.stringMatching dentro de 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.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));
});
});

Assertion Count

expect.assertions(number)

expect.assertions(number) verifica que um certo número de verificações são chamadas durante um teste. Isto é frequentemente útil ao testar código assíncrono, a fim de certificar-se que as verificações de um "callback" realmente tenham sido chamadas.

Por exemplo, digamos que temos uma função doAsync que recebe duas "callbacks" callback1 e callback2, de forma assíncrona chamará as duas numa ordem desconhecida. Podemos testar isso com:

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

doAsync(callback1, callback2);
});

A chamada expect.assertions(2) garante que as duas "callbacks" sejam realmente chamadas.

expect.hasAssertions()

expect.hasAssertions() verifica que pelo menos uma verificação é chamada durante um teste. Isto é frequentemente útil ao testar código assíncrono, a fim de certificar-se que as verificações de um "callback" realmente tenham sido chamadas.

Por exemplo, digamos que nós temos algumas funções onde todas lidam com estado. prepareState chama um "callback" com um objeto de estado, validateState é executado nesse objeto de estado, e waitOnState retorna uma promessa que aguarda até que todas as "callbacks" prepareState completem. Podemos testar isso com:

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

A chamada expect.hasAssertions() garante que a "callback" prepareState é realmente chamada.

Extend Utilities

expect.addEqualityTesters(testers)

You can use expect.addEqualityTesters to add your own methods to test if two objects are equal. For example, let's say you have a class in your code that represents volume and can determine if two volumes using different units are equal. You may want toEqual (and other equality matchers) to use this custom equality method when comparing to Volume classes. You can add a custom equality tester to have toEqual detect and apply custom logic when comparing Volume classes:

Volume.js
// For simplicity in this example, we'll just support the units 'L' and 'mL'
export class Volume {
constructor(amount, unit) {
this.amount = amount;
this.unit = unit;
}

toString() {
return `[Volume ${this.amount}${this.unit}]`;
}

equals(other) {
if (this.unit === other.unit) {
return this.amount === other.amount;
} else if (this.unit === 'L' && other.unit === 'mL') {
return this.amount * 1000 === other.unit;
} else {
return this.amount === other.unit * 1000;
}
}
}
areVolumesEqual.js
import {expect} from '@jest/globals';
import {Volume} from './Volume.js';

function areVolumesEqual(a, b) {
const isAVolume = a instanceof Volume;
const isBVolume = b instanceof Volume;

if (isAVolume && isBVolume) {
return a.equals(b);
} else if (isAVolume === isBVolume) {
return undefined;
} else {
return false;
}
}

expect.addEqualityTesters([areVolumesEqual]);
__tests__/Volume.test.js
import {expect, test} from '@jest/globals';
import {Volume} from '../Volume.js';
import '../areVolumesEqual.js';

test('are equal with different units', () => {
expect(new Volume(1, 'L')).toEqual(new Volume(1000, 'mL'));
});

Custom equality testers API

Custom testers are functions that return either the result (true or false) of comparing the equality of the two given arguments or undefined if the tester does not handle the given objects and wants to delegate equality to other testers (for example, the builtin equality testers).

Custom testers are called with 3 arguments: the two objects to compare and the array of custom testers (used for recursive testers, see the section below).

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

this.equals(a, b, customTesters?)

Esta é uma função de igualdade profunda que retornará true se dois objetos têm os mesmos valores (recursivamente). It optionally takes a list of custom equality testers to apply to the deep equality checks. If you use this function, pass through the custom testers your tester is given so further equality checks equals applies can also use custom testers the test author may have configured. See the example in the Recursive custom equality testers section for more details.

Matchers vs Testers

Matchers are methods available on expect, for example expect().toEqual(). toEqual is a matcher. A tester is a method used by matchers that do equality checks to determine if objects are the same.

Custom matchers are good to use when you want to provide a custom assertion that test authors can use in their tests. For example, the toBeWithinRange example in the expect.extend section is a good example of a custom matcher. Sometimes a test author may want to assert two numbers are exactly equal and should use toBe. Other times, however, a test author may want to allow for some flexibility in their test, and toBeWithinRange may be a more appropriate assertion.

Custom equality testers are good for globally extending Jest matchers to apply custom equality logic for all equality comparisons. Test authors can't turn on custom testers for certain assertions and turn them off for others (a custom matcher should be used instead if that behavior is desired). For example, defining how to check if two Volume objects are equal for all matchers would be a good custom equality tester.

Recursive custom equality testers

If your custom equality testers are testing objects with properties you'd like to do deep equality with, you should use the this.equals helper available to equality testers. This equals method is the same deep equals method Jest uses internally for all of its deep equality comparisons. It's the method that invokes your custom equality tester. It accepts an array of custom equality testers as a third argument. Custom equality testers are also given an array of custom testers as their third argument. Pass this argument into the third argument of equals so that any further equality checks deeper into your object can also take advantage of custom equality testers.

For example, let's say you have a Book class that contains an array of Author classes and both of these classes have custom testers. The Book custom tester would want to do a deep equality check on the array of Authors and pass in the custom testers given to it, so the Authors custom equality tester is applied:

customEqualityTesters.js
function areAuthorEqual(a, b) {
const isAAuthor = a instanceof Author;
const isBAuthor = b instanceof Author;

if (isAAuthor && isBAuthor) {
// Authors are equal if they have the same name
return a.name === b.name;
} else if (isAAuthor === isBAuthor) {
return undefined;
} else {
return false;
}
}

function areBooksEqual(a, b, customTesters) {
const isABook = a instanceof Book;
const isBBook = b instanceof Book;

if (isABook && isBBook) {
// Books are the same if they have the same name and author array. We need
// to pass customTesters to equals here so the Author custom tester will be
// used when comparing Authors
return (
a.name === b.name && this.equals(a.authors, b.authors, customTesters)
);
} else if (isABook === isBBook) {
return undefined;
} else {
return false;
}
}

expect.addEqualityTesters([areAuthorsEqual, areBooksEqual]);
note

Remember to define your equality testers as regular functions and not arrow functions in order to access the tester context helpers (e.g. this.equals).

expect.addSnapshotSerializer(serializer)

Você pode chamar expect.addSnapshotSerializer para adicionar um módulo que formata estruturas de dados específicas da aplicação.

Para um arquivo de teste individual, um módulo adicionado precede quaisquer módulos da configuração snapshotSerializers, que precedem os serializadores de snapshot padrão para tipos internos de JavaScript e para elementos React. O último módulo adicionado é o primeiro módulo testado.

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.

Consulte configurando Jest para obter maiores informações.

expect.extend(matchers)

Você pode usar expect.extend para adicionar seus próprios "matchers" em Jest. Por exemplo, vamos dizer que você esta testando uma biblioteca de números e você esta frequentemente afirmando que os números aparecem em intervalos específicos de outros números. Você pode abstrair isso dentro do matcher toBeWithinRange:

toBeWithinRange.js
import {expect} from '@jest/globals';

function toBeWithinRange(actual, floor, ceiling) {
if (
typeof actual !== 'number' ||
typeof floor !== 'number' ||
typeof ceiling !== 'number'
) {
throw new TypeError('These must be of type number!');
}

const pass = actual >= floor && actual <= ceiling;
if (pass) {
return {
message: () =>
`expected ${this.utils.printReceived(
actual,
)} not to be within range ${this.utils.printExpected(
`${floor} - ${ceiling}`,
)}`,
pass: true,
};
} else {
return {
message: () =>
`expected ${this.utils.printReceived(
actual,
)} to be within range ${this.utils.printExpected(
`${floor} - ${ceiling}`,
)}`,
pass: false,
};
}
}

expect.extend({
toBeWithinRange,
});
__tests__/ranges.test.js
import {expect, test} from '@jest/globals';
import '../toBeWithinRange';

test('is within range', () => expect(100).toBeWithinRange(90, 110));

test('is NOT within range', () => expect(101).not.toBeWithinRange(0, 100));

test('asymmetric ranges', () => {
expect({apples: 6, bananas: 3}).toEqual({
apples: expect.toBeWithinRange(1, 10),
bananas: expect.not.toBeWithinRange(11, 20),
});
});
toBeWithinRange.d.ts
// optionally add a type declaration, e.g. it enables autocompletion in IDEs
declare module 'expect' {
interface AsymmetricMatchers {
toBeWithinRange(floor: number, ceiling: number): void;
}
interface Matchers<R> {
toBeWithinRange(floor: number, ceiling: number): R;
}
}

export {};
tip

The type declaration of the matcher can live in a .d.ts file or in an imported .ts module (see JS and TS examples above respectively). If you keep the declaration in a .d.ts file, make sure that it is included in the program and that it is a valid module, i.e. it has at least an empty export {}.

tip

Instead of importing toBeWithinRange module to the test file, you can enable the matcher for all tests by moving the expect.extend call to a setupFilesAfterEnv script:

import {expect} from '@jest/globals';
// remember to export `toBeWithinRange` as well
import {toBeWithinRange} from './toBeWithinRange';

expect.extend({
toBeWithinRange,
});

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

Os Matchers devem retornar um objeto (ou uma Promessa de um objeto) com duas chaves. pass indica se houve ou não uma correspondência, e message fornece uma função sem argumentos que retorna uma mensagem de erro em caso de falha. Assim, quando pass é falso, message deve retornar a mensagem de erro quando expect(x).yourMatcher() falha. E quando pass é verdadeiro, a mensagem deve retornar a mensagem de erro quando expect(x).not.yourMatcher() falha.

Matchers são chamados com o argumento passado para expect(x) seguido dos argumentos passados para .yourMatcher(y, z):

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

Essas funções e propriedades auxiliares podem ser encontradas em este dentro de um "matcher" personalizado:

this.isNot

Um valor booleano para que você saiba que este "matcher" foi chamado com o negado .not modificador permitindo que você exiba uma dica de "matcher" clara e correta (veja código de exemplo).

this.promise

Uma string permitindo que você exiba uma dica de "matcher" clara e correta:

  • '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, customTesters?)

Esta é uma função de igualdade profunda que retornará true se dois objetos têm os mesmos valores (recursivamente). It optionally takes a list of custom equality testers to apply to the deep equality checks (see this.customTesters below).

this.expand

Um valor booleano para que você saiba que este "matcher" foi chamado com uma opção de expand. 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.

Os mais úteis são matcherHint, printExpected e printReceived para formatar bem as mensagens de erro. Por exemplo, dê uma olhada na implementação para o "matcher" 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};
},
});

Isto imprimirá algo como:

  expect(received).toBe(expected)

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

Quando uma verificação falha, a mensagem de erro deve dar o máximo de informação necessária para o usuário, para que eles possam resolver seu problema rapidamente. Você deve criar uma mensagem de falha precisa para certificar-se de que os usuários de suas verificações personalizados tenham uma boa experiência de desenvolvimento.

this.customTesters

If your matcher does a deep equality check using this.equals, you may want to pass user-provided custom testers to this.equals. The custom equality testers the user has provided using the addEqualityTesters API are available on this property. The built-in Jest matchers pass this.customTesters (along with other built-in testers) to this.equals to do deep equality, and your custom matchers may want to do the same.

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.slice(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"`;
*/

Também é possível criar "matchers" personalizados para snapshots em linhas, os snapshots serão adicionados corretamente aos "matchers" personalizados. No entanto, o snapshot em linha sempre tentará anexar ao primeiro argumento ou ao segundo quando o primeiro argumento for o matcher da propriedade, portanto, não é possível aceitar argumentos personalizados nos "matchers" personalizados.

const {toMatchInlineSnapshot} = require('jest-snapshot');

expect.extend({
toMatchTrimmedInlineSnapshot(received, ...rest) {
return toMatchInlineSnapshot.call(this, received.slice(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

Se o seu snapshot em linha personalizado estiver assíncrono, Use async-await talvez você possa encontrar um erro como "Múltiplos snapshots em linha para a mesma chamada não são suportados". 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"`);
});