Expect
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.
For additional Jest matchers maintained by the Jest Community check out jest-extended
.
Métodos
expect(value)
expect.extend(matchers)
expect.anything()
expect.any(constructor)
expect.arrayContaining(array)
expect.assertions(number)
expect.hasAssertions()
expect.not.arrayContaining(array)
expect.not.objectContaining(object)
expect.not.stringContaining(string)
expect.not.stringMatching(string | regexp)
expect.objectContaining(object)
expect.stringContaining(string)
expect.stringMatching(string | regexp)
expect.addSnapshotSerializer(serializer)
.not
.resolves
.rejects
.toBe(value)
.toHaveBeenCalled()
.toHaveBeenCalledTimes(number)
.toHaveBeenCalledWith(arg1, arg2, ...)
.toHaveBeenLastCalledWith(arg1, arg2, ...)
.toHaveBeenNthCalledWith(nthCall, arg1, arg2, ....)
.toHaveReturned()
.toHaveReturnedTimes(number)
.toHaveReturnedWith(value)
.toHaveLastReturnedWith(value)
.toHaveNthReturnedWith(nthCall, value)
.toHaveLength(number)
.toHaveProperty(pathLlave, valor?)
.toBeCloseTo(número, númeroDigitos?)
.toBeDefined()
.toBeFalsy()
.toBeGreaterThan(número)
.toBeGreaterThanOrEqual(número)
.toBeLessThan(número)
.toBeLessThanOrEqual(número)
.toBeInstanceOf(Class)
.toBeNull()
.toBeTruthy()
.toBeUndefined()
.toBeNaN()
.toContain(item)
.toContainEqual(item)
.toEqual(value)
.toMatch(regexp | string)
.toMatchObject(object)
.toMatchSnapshot(propertyMatchers?, hint?)
.toMatchInlineSnapshot(propertyMatchers?, inlineSnapshot)
.toStrictEqual(value)
.toThrow(error?)
.toThrowErrorMatchingSnapshot(hint?)
.toThrowErrorMatchingInlineSnapshot(inlineSnapshot)
Referencia
expect(value)
La función expect
se utiliza cada vez que desea testear un valor. Rara vez se utiliza expect
por sí mismo. En su lugar, utilizarás expect
junto a una función de "comparación" para afirmar algo sobre un valor.
Es más fácil entenderlo con este ejemplo. Digamos que tenemos un método mejorSabor()
que se supone que devuelve el texto 'grapefruit'
. Así es cómo sería el test:
test('el mejor sabor es de melocotón', () => {
expect(mejorSabor()).toBe('melocotón');
});
In this case, toBe
is the matcher function. There are a lot of different matcher functions, documented below, to help you test different things.
El argumento expect
debe ser el valor que produce tu código, y cualquier argumento de comparación debe ser el valor correcto. Si los mezclas, tus test problablemente seguiran funcionando, pero los mensajes de error seran confusos.
expect.extend(matchers)
Puedes utilizar expect.extend
para añadir tus propios comparadores a Jest. 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),
});
});
Note: In TypeScript, when using @types/jest
for example, you can declare the new toBeWithinRange
matcher like this:
declare global {
namespace jest {
interface Matchers<R> {
toBeWithinRange(a: number, b: number): R;
}
}
}
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
indica si hubo un acierto o no, y message
proporciona una función sin argumentos que devuelve un mensaje de error en caso de fallo. Así, cuando pass
es falso, message
debe devolver el mensaje de error para cuando expect(x).tuComparador()
. Y cuando pass
es 'true', message
debe devolver el mensaje de error para cuando expect(x).not.tuComparador()
.
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)
Esta es una función de igualdad profunda que regresará true
si dos objetos tienen los mismos valores (recursivamente).
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
Hay un número de herramientas de utilidad reveladas en this.utils
que consisten en las funciones de jest-matcher-utils
.
Las más útiles son matcherHint
, printExpected
y printReceived
para dar formato mas agradable a los mensajes de error. Por ejemplo, echa un vistazo en la implementación para el comparador 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
? () =>
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 (
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};
},
});
Esto mostrará algo así:
expect(received).toBe(expected)
Expected value to be (using Object.is):
"banana"
Received:
"apple"
Cuando una afirmación falla, el mensaje de error debería dar las señales necesarias para que el usuario pueda resolver sus problemas rápidamente. Deberías crear mensajes de errores precisos para que los usuarios de tus afirmaciones personalizadas se sientan cómodos usándolas.
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"`;
*/
expect.anything()
expect.anything()
aprobará cualquier cosa excepto null
o undefined
. Pedes usarlo dentro de toEqual
o toBeCalledWith
en vez de usar un valor literal. Por ejemplo, si quieres asegurarte de que un mock ha sido llamado con un argumento que no sea null:
test('map calls its argument with a non-null argument', () => {
const mock = jest.fn();
[1].map(x => mock(x));
expect(mock).toBeCalledWith(expect.anything());
});
expect.any(constructor)
expect.any(constructor)
aprueba cualquier cosa que sea creada con el constructor recibido. Pedes usarlo dentro de toEqual
o toBeCalledWith
en vez de usar un valor literal. Por ejemplo, si quieres asegurarte de que un mock ha sido llamado con un número:
function randocall(fn) {
return fn(Math.floor(Math.random() * 6 + 1));
}
test('randocall calls its callback with a number', () => {
const mock = jest.fn();
randocall(mock);
expect(mock).toBeCalledWith(expect.any(Number));
});
expect.arrayContaining(array)
expect.arrayContaining(array)
aprueba que la matriz recibida contiene todos los elementos de la matriz esperada. Eso significa que la matriz esperada es un subconjunto de la matriz recibida. Por tanto, aprueba una matriz recibida que contenga elementos que no estén en la matriz esperada.
Puedes utilizarla en vez de usar un valor literal:
- en
toEqual
otoBeCalledWith
- para aprobar una propiedad en
objectContaining
otoMatchObject
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)
verifica que un cierto número de afirmaciones han sido realizadas durante un test. Esto es útil a la hora de probar código asíncrono para asegurarnos de que las afirmaciones de un callback fueron llamadas.
Por ejemplo, supongamos que tenemos una función doAsync
que recibe dos devoluciones de llamada callback1
y callback2
, asincrónicamente se llamará a ambas en un orden desconocido. Podemos comprobarlo con:
test('doAsync llama a ambos callbacks', () => {
expect.assertions(2);
function callback1(data) {
expect(data).toBeTruthy();
}
function callback2(data) {
expect(data).toBeTruthy();
}
doAsync(callback1, callback2);
});
La llamada de expect.assertions(2)
asegura que ambas devoluciones de llamada son efectivamente ejecutadas.
expect.hasAssertions()
expect.hasAssertions()
verifica que al menos una verificación es llamada durante un test. Esto es útil a la hora de probar código asíncrono para asegurarnos de que las afirmaciones de un callback fueron llamadas.
Por ejemplo, digamos que tenemos unas pocas funciones y todas tratan con un estado. prepareState
llama a una devolución de llamada con un objeto de estado, validateState
se ejecuta en este objeto de estado, y waitOnState
devuelve una promesa que espera hasta que las devoluciones de llamada de prepareState
completen. Podemos comprobarlo con:
test('prepareState prepara un estado valido', () => {
expect.hasAssertions();
prepareState(state => {
expect(validateState(estado)).toBeTruthy();
});
return waitOnState();
});
La llamada de expect.hasAssertions()
asegura que ambas devoluciones de llamada de prepareState
son efectivamente ejecutadas.
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. De tal manera que, hace match con un objeto que contiene propiedades que no se encuentran en el objeto esperado.
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)
compara recursivamente con cualquier objeto recibido que cumpla con las propiedades esperadas. Es decir, el objeto esperado es un subconjunto del objeto recibido. Therefore, it matches a received object which contains properties that are present in the expected object.
En lugar de verificar los valores de propiedades en el objeto esperado, se pueden ocupar matchers, como expect.anything()
, entre otros.
Por ejemplo, si se espera que la función onPress
sea llamada con el objeto Event
, y solo se necesita verificar que el evento tiene las propiedades event.x
y event.y
. Puedes hacer esto con:
test('onPress gets called with the right thing', () => {
const onPress = jest.fn();
simulatePresses(onPress);
expect(onPress).toBeCalledWith(
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.
Puedes utilizarla en vez de usar un valor literal:
- en
toEqual
otoBeCalledWith
- para que coincida con un elemento en
arrayContaining
- para aprobar una propiedad en
objectContaining
otoMatchObject
Este ejemplo también muestra cómo se pueden anidar múltiples marcadores de comparación asimétricas, con 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.addSnapshotSerializer(serializer)
Puedes llamar a expect.addSnapshotSerializer
para agregar un módulo que formatee estructuras de datos específicas de la aplicación.
Para un archivo de test individual, un módulo añadido precede a los módulos de snapshotSerializers
en la configuración, que preceden los serializadores de instantánea predeterminados para tipos de JavaScript integrados y elementos de React. El último módulo añadido, es el primero módulo testeado.
import serializer from 'my-serializer-module';
expect.addSnapshotSerializer(serializer);
// afecta a las afirmaciones expect(value).toMatchSnapshot() en el archivo de test
If you add a snapshot serializer in individual test files instead of adding it to snapshotSerializers
configuration:
- Haces la dependencia explícita en lugar de implícita.
- Evitas límites de la configuración que podría causarte expulsar desde create-react-app.
Véase configurando Jest para más información.
.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('el mejor sabor no es coco', () => {
expect(mejorSaborLaCroix()).not.toBe('coco');
});
.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.
Por ejemplo, este código testea que la promesa resuelve y que el valor resultando es 'limon'
:
test('resuelve a limon', () => {
// Es esencial que se agregue un statement de return
return expect(Promise.resolve('limon')).resolves.toBe('limon');
});
Tenga en cuenta que, dado que todavía esta probando promesas, la prueba sigue siendo asincronica. Hence, you will need to tell Jest to wait by returning the unwrapped assertion.
Alternativamente, se puede usar async/await
en combinación con .resolves
:
test('resuelve a limon', async () => {
await expect(Promise.resolve('limon')).resolves.toBe('limon');
await expect(Promise.resolve('limon')).resolves.not.toBe('pulpo');
});
.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.
Por ejemplo, este código prueba que la promesa rechaza con la razón 'octopus'
:
test('rejects to octopus', () => {
// make sure to add a return statement
return expect(Promise.reject(new Error('octopus'))).rejects.toThrow(
'octopus',
);
});
Tenga en cuenta que, dado que todavía esta probando promesas, la prueba sigue siendo asincronica. Hence, you will need to tell Jest to wait by returning the unwrapped assertion.
Alternativamente, puede utilizar async/await
combinado con .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.
Por ejemplo, el código a continuación valida algunas propiedades del objeto lata
:
const lata = {
nombre: 'pomelo',
onzas : 12,
};
describe('la lata', () => {
test('tiene 12 onzas', () => {
expect(lata.onzas).toBe(12);
});
test('tiene un nombre sofisticado', () => {
expect(lata.nombre).toBe('pomelo');
});
});
Don't use .toBe
with floating-point numbers. Por ejemplo, debido al redondeo, en JavaScript 0,2 + 0,1
no es estrictamente igual a 0,3
. Si tienes números de punto flotante, prueba .toBeCloseTo
en su lugar.
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)
asexpect(Object.is(received, expected)).toBe(true)
- rewrite
expect(received).not.toBe(expected)
asexpect(Object.is(received, expected)).toBe(false)
.toHaveBeenCalled()
También bajo el alias: .toBeCalled()
Usa .toHaveBeenCalled
para asegurar que una función "mock" fue llamada.
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? Puedes hacerlo con esta serie de tests:
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)
Usa .toHaveBeenCalledTimes
para asegurar que una función "mock" se llamo un número de veces exacto.
Por ejemplo, digamos que tienes una función beberCada(beber, Array<sabor>)
que toma una función beber
y la aplica a un arreglo de bebidas. Puede que quieras comprobar que la función beber se llamó un numero exacto de veces. Puedes hacerlo con esta serie de tests:
test('beberCada bebe cada bebida', () => {
const beber = jest.fn();
beberCada(beber, ['limon', 'pulpo']);
expect(beber).toHaveBeenCalledTimes(2);
});
.toHaveBeenCalledWith(arg1, arg2, ...)
También bajo el alias: .toBeCalledWith()
Usa .toHaveBeenCalledWith
para asegurar que una función mock haya sido llamada con argumentos específicos.
Por ejemplo, digamos que tienes una bebida con una función registrar
, y aplicarATodo(f)
que aplica la función f
a todas las bebidas registradas. Para asegurarte que funciona, puedes escribir:
test('registro aplicado correctamente a La Croix naranja', () => {
const bebida = new LaCroix('naranja');
registrar(bebida);
const f = jest.fn();
aplicarATodo(f);
expect(f).toHaveBeenCalledWith(bebida);
});
.toHaveBeenLastCalledWith(arg1, arg2, ...)
También bajo el alias: .lastCalledWith(arg1, arg2, ...)
Si tienes una función mock, puedes usar .toHaveBeenLastCalledWith
para ver los argumentos con los que fue llamada la ultima vez. Por ejemplo digamos que tienes una función aplicarATodosLosSabores(f)
que aplica la función f
a diversos sabores, y quieres asegurarte que la ultima vez que se llama a esta función el último sabor al que se le aplica la función es 'mango'
. Puedes escribir:
test('aplicarATodosLosSabores deja el mango para el final', () => {
const bebida = jest.fn();
aplicarATodosLosSabores(bebida);
expect(bebida).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'
. Puedes escribir:
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
. Puedes escribir:
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
. Puedes escribir:
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. Puedes escribir:
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. Puedes escribir:
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. Puedes escribir:
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)
Utilice .toHaveLength
para verificar que un objeto tenga longitud de .length
y tenga cierto valor numérico.
Es especialmente útil para verificar el tamaño de cadenas o arreglos.
expect([1, 2, 3]).toHaveLength(3);
expect('abc').toHaveLength(3);
expect('').not.toHaveLength(5);
.toHaveProperty(pathLlave, valor?)
Utilice .toHaveProperty
para verificar si la propiedad en la referencia de pathLlave
existe para un objeto dado. 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).
El siguiente ejemplo contiene un objeto casaEnVenta
con propiedades anidadas. 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(número, númeroDigitos?)
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);
});
.toBeDefined()
Usa .toBeDefined
para verificar que una variable no sea undefined. For example, if you want to check that a function fetchNewFlavorIdea()
returns something, you can write:
test('hay una nueva idea de sabor', () => {
expect(conseguirNuevaIdeaSabor()).toBeDefined();
});
Puedes escribir expect(conseguirNuevaIdeaSabor()).not.toBe(undefined)
, pero es buena practica omitir el uso de undefined
directamente en el 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:
beberPocoLaCroix();
if (!conseguirErrores()) {
beberMasLaCroix();
}
Puede que no te importe el valor que conseguirErrores
regrese, específicamente - podría regresar false
, null
, o 0
, y el código funcionaría correctamente. Si quieres probar que no hay errores después de tomar algo de La Croix, podrías escribir:
test('beber LaCroix no provoca errores', () => {
beberPocoLaCroix();
expect(conseguirErrores()).toBeFalsy();
});
In JavaScript, there are six falsy values: false
, 0
, ''
, null
, undefined
, and NaN
. Everything else is truthy.
.toBeGreaterThan(número)
Use toBeGreaterThan
to compare received > expected
for numbers. For example, test that ouncesPerCan()
returns a value of more than 10 ounces:
test('onzas por lata es mayor a 10', () => {
expect(onzasPorLata()).toBeGreaterThan(10);
});
.toBeGreaterThanOrEqual(número)
Use toBeGreaterThanOrEqual
to compare received >= expected
for numbers. For example, test that ouncesPerCan()
returns a value of at least 12 ounces:
test('onzas por lata es por lo menos 12', () => {
expect(onzasPorLata()).toBeGreaterThanOrEqual(12);
});
.toBeLessThan(número)
Use toBeLessThan
to compare received < expected
for numbers. For example, test that ouncesPerCan()
returns a value of less than 20 ounces:
test('onzas por lata es menor a 20', () => {
expect(onzasPorLata()).toBeLessThan(20);
});
.toBeLessThanOrEqual(número)
Use toBeLessThanOrEqual
to compare received <= expected
for numbers. For example, test that ouncesPerCan()
returns a value of at most 12 ounces:
test('onzas por lata es a lo mucho 12', () => {
expect(onzasPorLata()).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); // avienta error
.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 regresa 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:
beberPocoLaCroix();
if (infoSed()) {
beberMasLaCroix();
}
Puede que no te importe el valor que infoSed
regrese, específicamente - podría regresar true
o un objeto complejo, y el código funcionaría correctamente. So if you want to test that thirstInfo
will be truthy after drinking some La Croix, you could write:
test('beber La Croix lleva a conseguir info de sed', () => {
beberPocoLaCroix();
expect(infoSed()).toBeTruthy();
});
In JavaScript, there are six falsy values: false
, 0
, ''
, null
, undefined
, and NaN
. Everything else is truthy.
.toBeUndefined()
Usa .toBeDefined
para verificar que una variable es undefined. Por ejemplo, si quieres verificar que la función mejorBebidaPorSabor(sabor)
regresa undefined
para el sabor 'pulpo'
, porque no existe ninguna bebida con sabor a pulpo que sepa bien:
test('la mejor bebida con sabor a pulpo es undefined', () => {
expect(mejorBebidaPorSabor('pulpo')).toBeUndefined();
});
Podría escribir expect(mejorBebidaPorSabor('pulpo')).toBe(undefined)
, pero es buena practica omitir el uso de undefined
directamente en el 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
when you want to check that an item is in an array. For testing the items in the array, this uses ===
, a strict equality check. .toContain
can also check whether a string is a substring of another string.
For example, if getAllFlavors()
returns an array of flavors and you want to be sure that lime
is in there, you can write:
test('la lista de sabores contiene lima', () => {
expect(conseguirTodosSabores()).toContain('lima');
});
.toContainEqual(item)
Use .toContainEqual
when you want to check that an item with a specific structure and values is contained in an array. For testing the items in the array, this matcher recursively checks the equality of all fields, rather than checking for object identity.
describe('mi bebida', () => {
test('es deliciosa y no es agría', () => {
const miBebida = {deliciosa: true, agria: false};
expect(misBebidas()).toContainEqual(miBebida);
});
});
.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 lata1 = {
sabor: 'toronja',
onzas: 12,
};
const lata2 = {
sabor: 'toronja',
onzas: 12,
};
describe('las latas de La Croix en mi escritorio', () => {
test('tienen las mismas propiedades', () => {
expect(lata1).toEqual(lata2);
});
test('no son la misma lata', () => {
expect(lata1).not.toBe(lata2);
});
});
Nota:
.toEqual
no realizara una verificación de igualdad profunda para dos errores. Sólo la propiedadmessage
de un error se verifica para comparar igualdad. Se recomienda utilizar el método.toThrow
para probar errores.
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)
asexpect(received.equals(expected)).toBe(true)
- rewrite
expect(received).not.toEqual(expected)
asexpect(received.equals(expected)).toBe(false)
.toMatch(regexp | string)
Utilice .toMatch
para verificar que la cadena coincida con una expresión regular (Regex).
Por ejemplo, puede que no sepas el valor exacto que ensayoSobreElMejorSabor()
regresa, pero sabes que es una cadena muy larga, y que la cadena toronja
es parte del contenido. Podemos probarlo con:
describe('un ensayo sobre el mejor sabor', () => {
test('menciona toronja', () => {
expect(ensayoSobreElMejorSabor()).toMatch(/toronja/);
expect(ensayoSobreElMejorSabor()).toMatch(new RegExp('toronja'));
});
});
Este método acepta también una cadena, con la que va a intentar coincidir:
describe('las toronjas son saludables', () => {
test('las toronjas son frutas', () => {
expect('toronjas').toMatch('fruta');
});
});
.toMatchObject(object)
Usa .toMatchObject
para comprobar que un objeto de JavaScript coincide con un subconjunto de las propiedades de un objeto. Hará match de objetos recibidos cuyas propiedades no están en el objeto esperado.
También se puede pasar un arreglo de objetos, en cuyo caso el método regresara true solo si cada objeto en el arreglo hace match (como descrito en toMatchObject
anteriormente) con el objeto correspondiente en el arreglo esperado. Esto es útil si se desea verificar que dos arreglos coinciden en el número de sus elementos, opuesto a arrayContaining
, lo cual permite que el arreglo recibido contenga elementos adicionales.
Se puede hacer match de propiedades a través de sus valores o con matchers.
const casaEnVenta = {
bañera: true,
habitaciones: 4,
cocina: {
amenidades: ['horno', 'estufa', 'lavadora'],
area: 20,
colorPared: 'blanco',
},
};
const casaDeseada = {
bañera: true,
cocina: {
amenidades: ['horno', 'estufa', 'lavadora'],
colorPared: expect.stringMatching(/blanco|amarillo/),
},
};
test('la casa tiene las propiedades deseadas', () => {
expect(casaEnVenta).toMatchObject(casaDeseada);
});
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 types as well as structure.
Differences from .toEqual
:
- Keys with
undefined
properties are checked. e.g.{a: undefined, b: 2}
does not match{b: 2}
when using.toStrictEqual
. - Array sparseness is checked. e.g.
[, 1]
does not match[undefined, 1]
when using.toStrictEqual
. - Object types are checked to be equal. e.g. A class instance with fields
a
andb
will not equal a literal object with fieldsa
andb
.
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?)
Utilice .toThrow
en una prueba para verificar que una función arroja un error cuando se llama. Por ejemplo, si deseamos probar que beberSabor('pulpo')
arroja un error, porque el sabor a pulpo es demasiado repugnante para beber, podemos escribir:
test('arroja error en pulpo', () => {
expect(() => {
beberSabor('pulpo');
}).toThrow();
});
Note: 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 ejemplo, digamos que el código de beberSabor
es el siguiente:
function beberSabor(sabor) {
if (sabor == 'pulpo') {
throw new ErrorSaborRepugnante('guac! sabor a pulpo');
}
// Funcionalidad extra
}
Podríamos probar que este error lanza una excepción de varias formas:
test('throws on octopus', () => {
function drinkOctopus() {
drinkFlavor('octopus');
}
// Test that the error message says "yuck" somewhere: these are equivalent
expect(drinkOctopus).toThrowError(/yuck/);
expect(drinkOctopus).toThrowError('yuck');
// Test the exact error message
expect(drinkOctopus).toThrowError(/^yuck, octopus flavor$/);
expect(drinkOctopus).toThrowError(new Error('yuck, octopus flavor'));
// Test that we get a DisgustingFlavorError
expect(drinkOctopus).toThrowError(DisgustingFlavorError);
});
.toThrowErrorMatchingSnapshot(hint?)
Utilice .toThrowErrorMatchingSnapshot
para probar que una función arroja un error igual al snapshot más reciente cuando es llamada.
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 ejemplo, digamos que tienes una función beberSabor
que arroja un error cuando el sabor es 'pulpo'
, y su código es el siguiente:
function beberSabor(sabor) {
if (sabor == 'pulpo') {
throw new ErrorSaborRepugnante('guac! sabor a pulpo');
}
// Funcionalidad extra
}
El test para esta función se verá así:
test('arroja error en pulpo', () => {
function beberPulpo() {
beberSabor('pulpo');
}
expect(beberPulpo).toThrowErrorMatchingSnapshot();
});
Y generará el siguiente snapshot:
exports[`drinking flavors throws on octopus 1`] = `"yuck, octopus flavor"`;
Echa un ojo a React Tree Snapshot Testing para más información sobre tests de instantánea.
.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.