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.
Metode
afterAll(fn, timeout)
afterEach(fn, timeout)
beforeAll(fn, timeout)
beforeEach(fn, timeout)
describe(name, fn)
describe.only(name, fn)
describe.skip(name, fn)
test(name, fn, timeout)
test.only(name, fn, timeout)
test.skip(name, fn)
Referințe
afterAll(fn, timeout)
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.
Acest lucru este adesea util dacă doriţi să curăţați unele configurări globale, care este utilizate între diferite teste.
De exemplu:
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();
});
});
Aici afterAll
asigură că cleanUpDatabase
este apelată după execuția tuturor testelor.
În cazul în care afterAll
este în interiorul unui bloc describe
, se va executa la sfârşitul blocului.
Dacă doriţi să rulaţi ceva logică de curățare după fiecare test, nu după toate testele, se poate utiliza afterEach
în schimb.
afterEach(fn, timeout)
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.
Acest lucru este adesea util dacă doriţi să curăţați unele configurări temporare, care sunt create în fiecare test.
De exemplu:
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();
});
});
Aici afterEach
asigură că cleanUpDatabase
este apelată după execuția fiecărui test în parte.
În cazul în care afterEach
este în interiorul unui bloc describe
, se va executa doar după fiecare test din interiorul blocului.
Dacă doriţi să rulaţi ceva logică de curățare doar o singură dată, după execuția tuturor testelor, utilizaţi afterAll
în schimb.
beforeAll(fn, timeout)
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.
Acest lucru este adesea util dacă doriţi să setați unele configurări globale, care vor fi utilizate de mai multe teste.
De exemplu:
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);
});
});
Aici beforeAll
asigură că baza de date este setată înainte de a rula testele. If setup was synchronous, you could do this without beforeAll
. Cheia este că Jest va aştepta pentru un Promise să se rezolve, astfel încât puteţi avea o configurare asincronă, de asemenea.
În cazul în care beforeAll
este în interiorul unui bloc describe
, se va executa la începutul blocului.
Dacă doriţi să rulaţi ceva logică înaintea fiecărui test, nu înainte de toate testele, se poate utiliza beforeEach
în schimb.
beforeEach(fn, timeout)
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.
Acest lucru este adesea util dacă doriţi să resetați unele configurări globale, care vor fi utilizate de mai multe teste.
De exemplu:
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();
});
});
Aici beforeEach
asigură că baza de date este resetată înainte de fiecare test.
În cazul în care beforeEach
este în interiorul unui bloc describe
, se va executa înainte de fiecare test din interiorul blocului.
Dacă aveţi nevoie doar să rulați ceva cod de configurare o singură dată, înainte de orice test, utilizaţi beforeAll
.
describe(name, fn)
describe(name, fn)
creates a block that groups together several related tests. De exemplu, dacă aveţi un obiect myBeverage
, care se presupune a fi delicios, dar nu acru, aţi putea test acest lucru în felul următor:
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.
Puteţi, de asemenea, imbrica blocuri describe
în cazul în care aveţi o ierarhie de teste:
const binaryStringToNumber = binString => {
if (!/^[01]+$/.test(binString)) {
throw new CustomError('Not a binary number.');
}
return parseInt(binString, 2);
};
describe('binaryStringToNumber', () => {
describe('given an invalid binary string', () => {
test('composed of non-numbers throws CustomError', () => {
expect(() => binaryStringToNumber('abc')).toThrowError(CustomError);
});
test('with extra whitespace throws CustomError', () => {
expect(() => binaryStringToNumber(' 100')).toThrowError(CustomError);
});
});
describe('given a valid binary string', () => {
test('returns the correct number', () => {
expect(binaryStringToNumber('100')).toBe(4);
});
});
});
describe.only(name, fn)
Există și cu aliasul: fdescribe(name, fn)
Aveţi posibilitatea să utilizaţi describe.only
dacă doriţi să se execute un singur bloc describe:
describe.only('my beverage', () => {
test('is delicious', () => {
expect(myBeverage.delicious).toBeTruthy();
});
test('is not sour', () => {
expect(myBeverage.sour).toBeFalsy();
});
});
describe('my other beverage', () => {
// ... will be skipped
});
describe.skip(name, fn)
Există și cu aliasul: xdescribe(name, fn)
Aveţi posibilitatea să utilizaţi describe.skip
dacă nu doriţi să se execute un anumit bloc describe:
describe('my beverage', () => {
test('is delicious', () => {
expect(myBeverage.delicious).toBeTruthy();
});
test('is not sour', () => {
expect(myBeverage.sour).toBeFalsy();
});
});
describe.skip('my other beverage', () => {
// ... will be skipped
});
Using describe.skip
is often a cleaner alternative to temporarily commenting out a chunk of tests.
test(name, fn, timeout)
Also under the alias: it(name, fn, timeout)
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);
});
Primul argument este numele testului; al doilea argument este o funcţie care conţine aserțiunile pentru test. The third argument (optional) is timeout
(in milliseconds) for specifying how long to wait before aborting. Note: The default timeout is 5 seconds.
Notă: În cazul în care o promisiune este returnată din
test
, Jest va aştepta rezolvarea promisiunii înainte ca testul să se finalizeze. Jest va aştepta, de asemenea, și dacă pasați un argument la funcţia de test, numit de obiceidone
. Acest lucru ar putea fi util atunci când testați callback-uri. Aflaţi cum să testați cod asincron aici.
For example, let's say fetchBeverageList()
returns a promise that is supposed to resolve to a list that has lemon
in it. Puteți testa acest lucru în felul următor:
test('has lemon in it', () => {
return fetchBeverageList().then(list => {
expect(list).toContain('lemon');
});
});
Chiar dacă apelul pentru test
va returna imediat, testul nu se va finaliza doar după rezolvarea promisiunii.
test.only(name, fn, timeout)
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.
De exemplu, să presupunem că aveți aceste teste:
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)
Atunci când lucrați cu baze mari de cod, puteţi găsi, uneori, un test care este temporar stricat din diverse motive. 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.
De exemplu, să presupunem că aveți aceste teste:
test('it is raining', () => {
expect(inchesOfRain()).toBeGreaterThan(0);
});
test.skip('it is not snowing', () => {
expect(inchesOfSnow()).toBe(0);
});
Doar testul "it is raining" va rula, deoarece celălalt test este apelat cu test.skip
.
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.