Expect
Cuando estás escribiendo tests, a menudo necesitas comprobar que los valores cumplen ciertas condiciones. expect
te da acceso a un número de marcadores que te permiten validar diferentes cosas.
For additional Jest matchers maintained by the Jest Community check out jest-extended
.
The TypeScript examples from this page will only work as documented if you explicitly import Jest APIs:
import {expect, jest, test} from '@jest/globals';
Consult the Getting Started guide for details on how to setup Jest with TypeScript.
Referencia
- Expect
- Modifiers
- Matchers
.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(number | bigint)
.toBeGreaterThanOrEqual(number | bigint)
.toBeLessThan(number | bigint)
.toBeLessThanOrEqual(number | bigint)
.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)
- Asymmetric Matchers
expect.anything()
expect.any(constructor)
expect.arrayContaining(array)
expect.not.arrayContaining(array)
expect.closeTo(number, numDigits?)
expect.objectContaining(object)
expect.not.objectContaining(object)
expect.stringContaining(string)
expect.not.stringContaining(string)
expect.stringMatching(string | regexp)
expect.not.stringMatching(string | regexp)
- Assertion Count
- Extend Utilities
Expect
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');
});
En este caso, toBe
es la función de comparación. Hay una gran cantidad de funciones matcher diferentes, documentadas a continuación, para ayudarte a probar cosas diferentes.
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.
Modifiers
.not
Si sabes cómo testear algo, .no
te permite comprobar su opuesto. Por ejemplo, este código testea que el mejor sabor de La Croix no es coco:
import serializer from 'my-serializer-module';
expect.addSnapshotSerializer(serializer);
// afecta a las afirmaciones expect(value).toMatchSnapshot() en el archivo de test
.resolves
Utiliza resolves
para desenvolver el valor de una promesa cumplida, para que así cualquier otro marcados pueda ser encadenado. Si la promesa se rechaza la afirmación falla.
Por ejemplo, este código testea que la promesa resuelve y que el valor resultando es 'limon'
:
test('el mejor sabor no es coco', () => {
expect(mejorSaborLaCroix()).not.toBe('coco');
});
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.
Alternativamente, se puede usar async/await
en combinación con .resolves
:
test('resuelve a limon', () => {
// Es esencial que se agregue un statement de return
return expect(Promise.resolve('limon')).resolves.toBe('limon');
});
.rejects
Usa .rejects
para desenvolver el valor de una promesa cumplida, para que así cualquier otro marcados pueda ser encadenado. Si la promesa es rechazada la afirmación falla.
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',
);
});
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.
Alternativamente, puede utilizar async/await
combinado con .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 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 .toHaveBeenCalledWith
para asegurar que una función mock haya sido llamada con argumentos específicos. The arguments are checked with the same algorithm that .toEqual
uses.
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:
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.
For example, let's say you have a drinkAll(drink, flavour)
function that takes a drink
function and applies it to all available beverages. Puede que quieras comprobar que la función beber se llamó un numero exacto de veces. Puedes hacerlo con esta serie de tests:
test('aplicarATodosLosSabores deja el mango para el final', () => {
const bebida = jest.fn();
aplicarATodosLosSabores(bebida);
expect(bebida).toHaveBeenLastCalledWith('mango');
});
.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. The arguments are checked with the same algorithm that .toEqual
uses.
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('beberCada bebe cada bebida', () => {
const beber = jest.fn();
beberCada(beber, ['limon', 'pulpo']);
expect(beber).toHaveBeenCalledTimes(2);
});
.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('registro aplicado correctamente a La Croix naranja', () => {
const bebida = new LaCroix('naranja');
registrar(bebida);
const f = jest.fn();
aplicarATodo(f);
expect(f).toHaveBeenCalledWith(bebida);
});
.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');
});
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');
});