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.
Методи
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)
Довідка
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.
Це часто буває корисним якщо ви хочете очистити певний глобальний стан, спільний для різних тестів.
Наприклад:
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();
});
});
Тут afterAll
гарантує, що cleanUpDatabase
викликається після того, як виконаються всі тести.
Якщо afterAll
знаходиться всередині блоку describe
, він виконується в кінці цього блоку тестів.
Якщо ви хочете виконувати очистку після кожного тесту, використовуйте afterEach
взамін.
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.
Це часто буває корисним якщо ви хочете очистити певний тимчасовий стан, створений кожним з тестів.
Наприклад:
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();
});
});
Тут afterEach
гарантує, що cleanUpDatabase
викликається після виконання кожного тесту.
Якщо afterEach
знаходиться всередині блоку describe
, він виконується лише після кожного тесту всередині цього блоку.
Якщо ви хочете виконувати певну очистку тільки один раз після виконання всіх тестів, використовуйте afterAll
.
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.
Це часто буває корисним якщо ви хочете встановити певний глобальний стан, який буде використовуватися кількома тестами.
Наприклад:
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);
});
});
Тут beforeAll
гарантує, що база даних буде створена, перш ніж запускати тести. If setup was synchronous, you could do this without beforeAll
. Основна перевага полягає в тому, що Jest чекатиме, поки виконається проміс, що дозволяє використання асинхронних налаштувань.
Якщо beforeAll
знаходиться всередині блоку describe
, він виконується на початку цього блоку тестів.
Якщо ви хочете виконувати якісь команди перед запуском кожного тесту, використовуйте beforeEach
взамін.
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.
Це часто буває корисним якщо ви хочете перевстановити певний глобальний стан, який буде використовуватися кількома тестами.
Наприклад:
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();
});
});
Тут beforeEach
гарантує, що база даних буде створена заново перед кожним тестом.
Якщо beforeEach
знаходиться всередині блоку describe
, він виконується перед кожним тестом в цьому блоці.
Якщо вам потрібно виконати певні налаштування лише один раз перед запуском всіх тестів, використовуйте beforeAll
взамін.
describe(name, fn)
describe(name, fn)
creates a block that groups together several related tests. Наприклад, якщо у вас є об’єкт myBeverage
який повинен мати властивість delicious
і не мати властивості sour
, ви можете протестувати це так:
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.
Ви також можете вкладати блоки describe
один в одного якщо у вас є ієрахія тестів:
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)
Також має псевдонім fdescribe(name, fn)
Ви можете використовувати describe.only
, якщо ви хочете виконати лише один блок 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)
Також має псевдонім xdescribe(name, fn)
Ви можете використовувати describe.skip
, якщо ви не хочете запускати тести з певного блоку 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);
});
Перший аргумент - це назва тесту, другий - функція, яка містить очікування, які потрібно перевірити. 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. Ви можете протестувати це так:
test('has lemon in it', () => {
return fetchBeverageList().then(list => {
expect(list).toContain('lemon');
});
});
Незважаючи на те, що test
відразу поверне значення, тест не буде виконано, поки не буде виконано проміс.
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.
Наприклад, нехай у вас є наступні тести:
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)
Коли ви підтримуєте велику кодову базу, інколи може з’явитися, який тимчасово зламаний з якихось причин. 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.
Наприклад, нехай у вас є наступні тести:
test('it is raining', () => {
expect(inchesOfRain()).toBeGreaterThan(0);
});
test.skip('it is not snowing', () => {
expect(inchesOfSnow()).toBe(0);
});
Лише тест "it is raining" буде виконано, оскільки інший тест запускається з 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.