Globals
In your test files, Jest puts each of these methods and objects into the global environment. You don't have to require or import anything to use them.
Métodos
después de todo (fn, tiempo)
afterEach(fn, tiempo)
beforeAll(fn, tiempo)
beforeEach(fn, tiempo)
describe(name, fn)
describe.only(name, fn)
describe.skip(name, fn)
prueba(nombre, fn, tiempo)
prueba.solo(name, fn, tiempo)
test.skip(name, fn)
Referencia
después de todo (fn, tiempo)
Runs a function after all the tests in this file have completed. If the function returns a promise or is a generator, Jest waits for that promise to resolve before continuing.
Optionally, you can provide a timeout
(in milliseconds) for specifying how long to wait before aborting. Note: The default timeout is 5 seconds.
Esto es frecuentemente útil para restablecer el estado global compartido entre pruebas.
Por ejemplo:
const globalDatabase = makeGlobalDatabase();
function cleanUpDatabase(db) {
db.cleanUp();
}
afterAll(() => {
cleanUpDatabase(globalDatabase);
});
test('can find things', () => {
return globalDatabase.find('thing', {}, results => {
expect(results.length).toBeGreaterThan(0);
});
});
test('can insert a thing', () => {
return globalDatabase.insert('thing', makeThing(), response => {
expect(response.success).toBeTruthy();
});
});
La función afterAll
garantiza que el método cleanUpDatabase
sea llamado una vez terminada la ejecución de pruebas.
Si afterAll
es llamado dentro de un bloque describe
, este se ejecutará al final de la ejecución del bloque describe.
Si se desea ejecutar algún tipo de limpieza o restablecimiento después de cada prueba en lugar de al final de todas las pruebas, se puede utilizar afterEach
.
afterEach(fn, tiempo)
Runs a function after each one of the tests in this file completes. If the function returns a promise or is a generator, Jest waits for that promise to resolve before continuing.
Optionally, you can provide a timeout
(in milliseconds) for specifying how long to wait before aborting. Note: The default timeout is 5 seconds.
Esto es frecuentemente útil para restablecer algún estado temporal que sea creado por cada prueba.
Por ejemplo:
const globalDatabase = makeGlobalDatabase();
function cleanUpDatabase(db) {
db.cleanUp();
}
afterEach(() => {
cleanUpDatabase(globalDatabase);
});
test('can find things', () => {
return globalDatabase.find('thing', {}, results => {
expect(results.length).toBeGreaterThan(0);
});
});
test('can insert a thing', () => {
return globalDatabase.insert('thing', makeThing(), response => {
expect(response.success).toBeTruthy();
});
});
La función afterAll
garantiza que el método cleanUpDatabase
sea llamado una vez terminada cada prueba.
Si afterAll
es llamado dentro de un bloque describe
, este se ejecutará al final de la ejecución de cada prueba en el bloque describe.
Si se desea ejecutar algún tipo de limpieza o restablecimiento una sola vez por todas las pruebas, se puede utilizar afterAll
.
beforeAll(fn, tiempo)
Runs a function before any of the tests in this file run. If the function returns a promise or is a generator, Jest waits for that promise to resolve before running tests.
Optionally, you can provide a timeout
(in milliseconds) for specifying how long to wait before aborting. Note: The default timeout is 5 seconds.
Esto es frecuentemente útil para establecer algún estado global a ser ocupado por varias pruebas.
Por ejemplo:
const globalDatabase = makeGlobalDatabase();
beforeAll(() => {
// Clears the database and adds some testing data.
// Jest will wait for this promise to resolve before running tests.
return globalDatabase.clear().then(() => {
return globalDatabase.insert({testData: 'foo'});
});
});
// Since we only set up the database once in this example, it's important
// that our tests don't modify it.
test('can find things', () => {
return globalDatabase.find('thing', {}, results => {
expect(results.length).toBeGreaterThan(0);
});
});
Aquí el bloque beforeAll
garantiza que la base de datos sea configurada antes de que se ejecuten las pruebas. If setup was synchronous, you could do this without beforeAll
. La clave es que Jest espera a una promise para resolver, de modo que también se puede tener configuración inicial setup asincrona.
Si el bloque beforeAll
se encuentra dentro de un bloque describe
, esté se ejecutará al principio del bloque describe.
Si se desea ejecutar código antes de cada prueba en lugar de antes de todas las pruebas, se puede usar beforeEach
.
beforeEach(fn, tiempo)
Runs a function before each of the tests in this file runs. If the function returns a promise or is a generator, Jest waits for that promise to resolve before running the test.
Optionally, you can provide a timeout
(in milliseconds) for specifying how long to wait before aborting. Note: The default timeout is 5 seconds.
Esto es frecuentemente útil para restablecer algún estado global a ser ocupado por varias pruebas.
Por ejemplo:
const globalDatabase = makeGlobalDatabase();
beforeEach(() => {
// Clears the database and adds some testing data.
// Jest will wait for this promise to resolve before running tests.
return globalDatabase.clear().then(() => {
return globalDatabase.insert({testData: 'foo'});
});
});
test('can find things', () => {
return globalDatabase.find('thing', {}, results => {
expect(results.length).toBeGreaterThan(0);
});
});
test('can insert a thing', () => {
return globalDatabase.insert('thing', makeThing(), response => {
expect(response.success).toBeTruthy();
});
});
Aquí el bloque beforeAll
garantiza que la base de datos se restablezca antes de cada prueba.
Si el bloque beforeAll
se encuentra dentro de un bloque describe
, esté se ejecutará una vez antes de cada prueba en el bloque describe.
Si se desea ejecutar código de configuración inicial, una sola vez antes de cualquier prueba, usesé beforeAll
.
describe(name, fn)
describe(name, fn)
creates a block that groups together several related tests. Por ejemplo, si se tiene una objeto myBeverage
que representa una bebida que debe ser deliciosa pero no agria, se podría probar con:
const myBeverage = {
delicious: true,
sour: false,
};
describe('my beverage', () => {
test('is delicious', () => {
expect(myBeverage.delicious).toBeTruthy();
});
test('is not sour', () => {
expect(myBeverage.sour).toBeFalsy();
});
});
This isn't required - you can write the test
blocks directly at the top level. But this can be handy if you prefer your tests to be organized into groups.
También se pueden anidar bloques describe
si se tiene una jerarquía de pruebas:
const cadenaBinariaANumero = cadenaBinaria => {
if (!/^[01]+$/.test(cadenaBinaria)) {
throw new CustomError('No es un número binario.');
}
return parseInt(cadenaBinaria, 2);
};
describe('cadenaBinariaANumero', () => {
describe('dada una cadena binaria invalida', () => {
test('compuesta de no-números arroja un CustomError', () => {
expect(() => cadenaBinariaANumero('abc')).toThrowError(CustomError);
});
test('con espacios en blanco extra arroja un CustomError', () => {
expect(() => cadenaBinariaANumero(' 100')).toThrowError(CustomError);
});
});
describe('dada una cadena binaria valida', () => {
test('regresa el número correcto', () => {
expect(cadenaBinariaANumero('100')).toBe(4);
});
});
});
describe.only(name, fn)
Se puede encontrar también debajo del alias: fdescribe(name, fn)
Se puede utilizar describe.only
si se desea ejecutar solo ún bloque describe:
describe.only('mi bebida', () => {
test('es deliciosa', () => {
expect(miBebida.deliciosa).toBeTruthy();
});
test('no es amarga', () => {
expect(miBebida.amarga).toBeFalsy();
});
});
describe('mi otra bebida', () => {
// ... will be skipped
});
describe.skip(name, fn)
Se puede encontrar también debajo del alias: xdescribe(name, fn)
Se puede utilizar describe.skip
si se desea omitirun bloque describe en particular:
describe('mi bebida', () => {
test('es deliciosa', () => {
expect(miBebida.deliciosa).toBeTruthy();
});
test('no es amarga', () => {
expect(miBebida.amarga).toBeFalsy();
});
});
describe.skip('mi otra bebida', () => {
// ... will be skipped
});
Using describe.skip
is often a cleaner alternative to temporarily commenting out a chunk of tests.
prueba(nombre, fn, tiempo)
También con el alias: it(name, fn, tiempo)
All you need in a test file is the test
method which runs a test. For example, let's say there's a function inchesOfRain()
that should be zero. Your whole test could be:
test('did not rain', () => {
expect(inchesOfRain()).toBe(0);
});
El primer argumento es el nombre de la prueba, el segundo argumento es una función con el codigo de expectativas a ser probadas. The third argument (optional) is timeout
(in milliseconds) for specifying how long to wait before aborting. Note: The default timeout is 5 seconds.
Note: If a promise is returned from
test
, Jest will wait for the promise to resolve before letting the test complete. Jest will also wait if you provide an argument to the test function, usually calleddone
. This could be handy when you want to test callbacks. See how to test async code here.
For example, let's say fetchBeverageList()
returns a promise that is supposed to resolve to a list that has lemon
in it. Podemos probarlo con:
test('has lemon in it', () => {
return fetchBeverageList().then(list => {
expect(list).toContain('lemon');
});
});
Aunque la llamada al test
terminará inmediatamente, la prueba no será completada hasta que resuelva el promise.
prueba.solo(name, fn, tiempo)
Also under the aliases: it.only(name, fn, timeout)
, and fit(name, fn, timeout)
When you are debugging a large test file, you will often only want to run a subset of tests. You can use .only
to specify which tests are the only ones you want to run in that test file.
Optionally, you can provide a timeout
(in milliseconds) for specifying how long to wait before aborting. Note: The default timeout is 5 seconds.
Por ejemplo, digamos que se tuviera estas pruebas:
test.only('it is raining', () => {
expect(inchesOfRain()).toBeGreaterThan(0);
});
test('it is not snowing', () => {
expect(inchesOfSnow()).toBe(0);
});
Only the "it is raining" test will run in that test file, since it is run with test.only
.
Usually you wouldn't check code using test.only
into source control - you would use it for debugging, and remove it once you have fixed the broken tests.
test.skip(name, fn)
Also under the aliases: it.skip(name, fn)
, xit(name, fn)
, and xtest(name, fn)
Cuando se trabaja en una gran base de código, es frecuente encontrar alguna prueba que falla de manera temporal. If you want to skip running this test, but you don't want to delete this code, you can use test.skip
to specify some tests to skip.
Por ejemplo, digamos que se tuviera estas pruebas:
test('it is raining', () => {
expect(inchesOfRain()).toBeGreaterThan(0);
});
test.skip('it is not snowing', () => {
expect(inchesOfSnow()).toBe(0);
});
Sólo se ejecutaría la prueba "it is raning", pues se agregó test.skip
a la otra prueba.
You could comment the test out, but it's often a bit nicer to use test.skip
because it will maintain indentation and syntax highlighting.