Глобальні методи
Під час виконання тестів, Jest додає кожен з цих методів і об’єктів в глобальну область видимості. Вам не потрібно нічого підключати або імпортувати, щоб їх використовувати. Проте, якщо ви надаєте перевагу явним імпортам, ви можете робити це з допомогою import {describe, expect, test} from '@jest/globals'
.
Методи
afterAll(fn, timeout)
afterEach(fn, timeout)
beforeAll(fn, timeout)
beforeEach(fn, timeout)
describe(name, fn)
describe.each(table)(name, fn, timeout)
describe.only(name, fn)
describe.only.each(table)(name, fn)
describe.skip(name, fn)
describe.skip.each(table)(name, fn)
test(name, fn, timeout)
test.concurrent(name, fn, timeout)
test.concurrent.each(table)(name, fn, timeout)
test.concurrent.only.each(table)(name, fn)
test.concurrent.skip.each(table)(name, fn)
test.each(table)(name, fn, timeout)
test.only(name, fn, timeout)
test.only.each(table)(name, fn)
test.skip(name, fn)
test.skip.each(table)(name, fn)
test.todo(name)
Reference
afterAll(fn, timeout)
Запускає функцію після завершення усіх тестів у цьому файлі. Якщо функція повертає проміс, або генератор, Jest очікує на виконання цього промісу, перш ніж продовжити.
Додатково, ви можете вказати timeout
(у мілісекундах) на те як довго чекати перед перериванням. Примітка: за замовчуванням тайм-аут становить 5 секунд.
Часто це буває корисним, якщо ви хочете очистити певний глобальний стан, спільний для різних тестів.
Наприклад:
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)
Запускає функцію після завершення кожного тесту в цьому файлі. Якщо функція повертає проміс, або генератор, Jest очікує на виконання цього промісу, перш ніж продовжити.
Додатково, ви можете вказати timeout
(у мілісекундах) на те як довго чекати перед перериванням. Примітка: за замовчуванням тайм-аут становить 5 секунд.
Наприклад:
Наприклад:
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
, то функція запуститься після виконання усіх тестів у цьому describe
блоку.
Якщо ви хочете виконати певну очистку тільки один раз після виконання всіх тестів, використовуйте afterAll
.
beforeAll(fn, timeout)
Виконує функцію до запуску тестів в цьому файлі. Якщо функція повертає проміс, або генератор, Jest очікує на виконання цього промісу, перш ніж запускати тести.
Додатково, ви можете вказати timeout
(у мілісекундах) на те як довго чекати перед перериванням. Примітка: за замовчуванням тайм-аут становить 5 секунд.
Наприклад:
Наприклад:
const globalDatabase = makeGlobalDatabase();
beforeAll(() => {
// Очищає базу даних і додає деякі тестові дані.
// Jest чекатиме поки цей проміс буде виконано перед запуском тестів.
return globalDatabase.clear().then(() => {
return globalDatabase.insert({testData: 'foo'});
});
});
// Оскільки ми створили базу даних тільки один раз, в цьому прикладі, то важливо
// щоб наші тести не змінювали її
test('can find things', () => {
return globalDatabase.find('thing', {}, results => {
expect(results.length).toBeGreaterThan(0);
});
});
Тут beforeAll
гарантує, що база даних буде створена, перед запуском тестів. Якщо налаштування були синхронними, ви можете зробити це без beforeAll
. Основна перевага полягає в тому, що Jest чекатиме, поки виконається проміс, що дозволяє використання асинхронних налаштувань.
Якщо beforeAll
знаходиться всередині describe
блоку, функція запуститься на початку цього блоку.
Якщо ви хочете виконувати якісь команди перед запуском кожного тесту, використовуйте beforeEach
натомість.
beforeEach(fn, timeout)
Запускає функцію перед виконанням кожного тесту в цьому файлі. Якщо функція повертає проміс, або генератор, Jest очікує на виконання цього промісу, перш ніж запускати тест.
Додатково, ви можете вказати timeout
(у мілісекундах) на те як довго чекати перед перериванням. Примітка: за замовчуванням тайм-аут становить 5 секунд.
Наприклад:
Наприклад:
const globalDatabase = makeGlobalDatabase();
beforeEach(() => {
// Очищує базу даних та додає деякі тестові дані.
// Jest чекатиме поки цей проміс буде виконано перед запуском тестів.
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
блоку, то вона запуститься для кожного тесту в describe
блоці.
Якщо вам потрібно виконати певні налаштування лише один раз перед запуском всіх тестів, використовуйте beforeAll
натомість.
describe(name, fn)
describe(name, fn)
створює блок, який групує кілька пов'язаних тестів. Наприклад, якщо у вас є об’єкт 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();
});
});
Але це не обов'язково. Ви можете продовжувати використовувати test
блоки на верхньому рівні. Натомість це може бути досить зручно, якщо ви надаєте перевагу організації тестів по групах.
Ви також можете вкладати блоки 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')).toThrow(CustomError);
});
test('with extra whitespace throws CustomError', () => {
expect(() => binaryStringToNumber(' 100')).toThrow(CustomError);
});
});
describe('given a valid binary string', () => {
test('returns the correct number', () => {
expect(binaryStringToNumber('100')).toBe(4);
});
});
});
describe.each(table)(name, fn, timeout)
Використовуйте describe.each
якщо дублюєте один і той самий тест з різними даними. describe.each
дозволяє записати тестовий набір один раз і далі передавати в нього дані.
describe.each
доступний з двома API:
1. describe.each(table)(name, fn, timeout)
table
:Array
масивів з аргументами, яки передаються в функціюfn
для кожного рядка.- Примітка якщо ви передасте в плаский масив примітивів, внутрішньо вона буде змаплена в таблицю
[1, 2, 3] -> [[1], [2], [3]]
- Примітка якщо ви передасте в плаский масив примітивів, внутрішньо вона буде змаплена в таблицю
name
:String
заголовок тестового набору.- Генеруйте унікальні заголовки тестів за допомогою позиційних вбудованих параметрів за допомогою
printf
formatting:%p
- pretty-format.%s
- Рядок (String).%d
- Число (Number).%i
- Ціле число (Integer).%f
- Число з плаваючою комою (Floating point value).%j
- JSON.%o
- Об'єкт (Object).%#
- Index of the test case.%%
- single percent sign ('%'). Це не розглядається як аргумент.
- Або ж генеруйте унікальні заголовки тестів шляхом впровадження властивостей об'єкту теста за допомогою
$variable
- To inject nested object values use you can supply a keyPath i.e.
$variable.path.to.value
- Ви можете використати
$#
для додавання індексу тесту - You cannot use
$variable
with theprintf
formatting except for%%
- To inject nested object values use you can supply a keyPath i.e.
- Генеруйте унікальні заголовки тестів за допомогою позиційних вбудованих параметрів за допомогою
fn
:Function
the suite of tests to be run, this is the function that will receive the parameters in each row as function arguments.- Додатково, ви можете надати
timeout
(у мілісекундах), щоб вказати, як довго чекати кожного рядка перед перериванням. Примітка: за замовчуванням тайм-аут становить 5 секунд.
Example:
describe.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', (a, b, expected) => {
test(`returns ${expected}`, () => {
expect(a + b).toBe(expected);
});
test(`returned value not be greater than ${expected}`, () => {
expect(a + b).not.toBeGreaterThan(expected);
});
test(`returned value not be less than ${expected}`, () => {
expect(a + b).not.toBeLessThan(expected);
});
});
describe.each([
{a: 1, b: 1, expected: 2},
{a: 1, b: 2, expected: 3},
{a: 2, b: 1, expected: 3},
])('.add($a, $b)', ({a, b, expected}) => {
test(`returns ${expected}`, () => {
expect(a + b).toBe(expected);
});
test(`returned value not be greater than ${expected}`, () => {
expect(a + b).not.toBeGreaterThan(expected);
});
test(`returned value not be less than ${expected}`, () => {
expect(a + b).not.toBeLessThan(expected);
});
});
2. describe.each`table`(name, fn, timeout)
table
:Tagged Template Literal
- First row of variable name column headings separated with
|
- One or more subsequent rows of data supplied as template literal expressions using
${value}
syntax.
- First row of variable name column headings separated with
name
:String
the title of the test suite, use$variable
to inject test data into the suite title from the tagged template expressions, and$#
for the index of the row.- To inject nested object values use you can supply a keyPath i.e.
$variable.path.to.value
- To inject nested object values use you can supply a keyPath i.e.
fn
:Function
the suite of tests to be run, this is the function that will receive the test data object.- Додатково, ви можете надати
timeout
(у мілісекундах), щоб вказати, як довго чекати кожного рядка перед перериванням. Примітка: за замовчуванням тайм-аут становить 5 секунд.
Example:
describe.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('$a + $b', ({a, b, expected}) => {
test(`returns ${expected}`, () => {
expect(a + b).toBe(expected);
});
test(`returned value not be greater than ${expected}`, () => {
expect(a + b).not.toBeGreaterThan(expected);
});
test(`returned value not be less than ${expected}`, () => {
expect(a + b).not.toBeLessThan(expected);
});
});
describe.only(name, fn)
Також має псевдонім fdescribe(name, fn)
Ви можете використовувати describe.skip
, якщо ви не хочете, щоб запускати тести з окремого блоку
:
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.only.each(table)(name, fn)
Також має псевдоніми: fdescribe.each(table)(name, fn)
і fdescribe.each`table`(name, fn)
Використовуйте describe.only.each
, якщо ви хочете запустити лише певні тести.
describe.only.each
доступний з двома API:
describe.only.each(table)(name, fn)
describe.only.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', (a, b, expected) => {
test(`returns ${expected}`, () => {
expect(a + b).toBe(expected);
});
});
test('will not be run', () => {
expect(1 / 0).toBe(Infinity);
});
describe.only.each`table`(name, fn)
describe.only.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', ({a, b, expected}) => {
test('passes', () => {
expect(a + b).toBe(expected);
});
});
test('will not be run', () => {
expect(1 / 0).toBe(Infinity);
});
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. Майте на увазі, що блок describe
все ще буде запускатися. Якщо у вас є деякі налаштування, які також слід скасувати, зробіть це в beforeAll
або beforeEach
.
describe.skip.each(table)(name, fn)
Також має псевдоніми: xdescribe.each(table)(name, fn)
і xdescribe.each`table`(name, fn)
Використовуйте describe.skip.each
, якщо ви хочете припинити виконувати набір тестів (data driven tests).
describe.skip.each
доступний з двома API:
describe.skip.each(table)(name, fn)
describe.skip.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', (a, b, expected) => {
test(`returns ${expected}`, () => {
expect(a + b).toBe(expected); // will not be run
});
});
test('will be run', () => {
expect(1 / 0).toBe(Infinity);
});
describe.skip.each`table`(name, fn)
describe.skip.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', ({a, b, expected}) => {
test('will not be run', () => {
expect(a + b).toBe(expected); // will not be run
});
});
test('will be run', () => {
expect(1 / 0).toBe(Infinity);
});
test(name, fn, timeout)
Також має псевдонім: it(name, fn, timeout)
Все що вам потрібно у файлі з тестами - це метод test
, який запускає тест. Наприклад, скажімо, є функція inchesOfRain()
, яка має дорівнювати нулю. Повний код тесту може виглядати так:
test('did not rain', () => {
expect(inchesOfRain()).toBe(0);
});
Перший аргумент - це назва тесту, другий - функція, яка містить очікування, які потрібно перевірити. Третій аргумент (необов'язковий) - timeout
(у мілісекундах) для визначення, як довго чекати перед перериванням. Примітка: за замовчуванням тайм-аут становить 5 секунд.
Примітка: якщо проміс повернуто з
test
, Jest чекатиме на виконання промісу, перед тим, як завершити тест. Jest також буде чекати, якщо ви підставите аргумент тестової функції, зазвичай називаєтьсяdone
. Це може бути зручним, коли ви захочете протестувати зворотні виклики (callbacks). Тут можна подивитися, як тестувати асинхронний код.
Наприклад, скажімо, fetchBeverageList()
повертає проміс, який повинен виконатися і повернути список, який містить lemon
у собі. Ви можете протестувати це так:
test('has lemon in it', () => {
return fetchBeverageList().then(list => {
expect(list).toContain('lemon');
});
});
Незважаючи на те, що test
відразу поверне значення, тест не буде виконано, поки не буде виконано проміс.
test.concurrent(name, fn, timeout)
Також має псевдонім: it.concurrent(name, fn, timeout)
Використовуйте test.concurrent
, якщо хочете запускати тест в конкурентному режимі.
Примітка:
test.concurrent
винятково експериментальна функція - дивися тут детальну інформацію про відсутні функції та інші проблеми
Перший аргумент - це назва тесту; другий - асинхронна функція, яка містить очікування для перевірки. Третій аргумент (необов'язковий) - timeout
(у мілісекундах) для визначення, як довго чекати перед перериванням. Примітка: за замовчуванням тайм-аут становить 5 секунд.
test.concurrent('addition of 2 numbers', async () => {
expect(5 + 3).toBe(8);
});
test.concurrent('subtraction 2 numbers', async () => {
expect(5 - 3).toBe(2);
});
Примітка: використовуйте
maxConcurrency
для того, щоб заборонити Jest одночасно виконувати більшу кількість тестів ніж зазначено
test.concurrent.each(table)(name, fn, timeout)
Також має псевдонім: it.concurrent.each(table)(name, fn, timeout)
Використовуйте test.concurrent.each
якщо ви дублюєте один і той самий тест з різними даними. test.each
allows you to write the test once and pass data in, the tests are all run asynchronously.
test.concurrent.each
доступний з двома API:
1. test.concurrent.each(table)(name, fn, timeout)
table
:Array
of Arrays with the arguments that are passed into the testfn
for each row.- Примітка якщо ви передасте в плаский масив примітивів, внутрішньо вона буде змаплена в таблицю
[1, 2, 3] -> [[1], [2], [3]]
- Примітка якщо ви передасте в плаский масив примітивів, внутрішньо вона буде змаплена в таблицю
назва
:Рядок
the title of the test block.- Генеруйте унікальні заголовки тестів за допомогою позиційних вбудованих параметрів за допомогою
printf
formatting:%p
- pretty-format.%s
- Рядок (String).%d
- Число (Number).%i
- Ціле число (Integer).%f
- Число з плаваючою комою (Floating point value).%j
- JSON.%o
- Об'єкт (Object).%#
- Index of the test case.%%
- single percent sign ('%'). Це не розглядається як аргумент.
- Генеруйте унікальні заголовки тестів за допомогою позиційних вбудованих параметрів за допомогою
fn
:Function
the test to be run, this is the function that will receive the parameters in each row as function arguments, this will have to be an asynchronous function.- Додатково, ви можете надати
timeout
(у мілісекундах), щоб вказати, як довго чекати кожного рядка перед перериванням. Примітка: за замовчуванням тайм-аут становить 5 секунд.
Example:
test.concurrent.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', async (a, b, expected) => {
expect(a + b).toBe(expected);
});
2. test.concurrent.each`table`(name, fn, timeout)
table
:Tagged Template Literal
- First row of variable name column headings separated with
|
- One or more subsequent rows of data supplied as template literal expressions using
${value}
syntax.
- First row of variable name column headings separated with
назва
:Рядок
the title of the test, use$variable
to inject test data into the test title from the tagged template expressions.- To inject nested object values use you can supply a keyPath i.e.
$variable.path.to.value
- To inject nested object values use you can supply a keyPath i.e.
fn
:Function
the test to be run, this is the function that will receive the test data object, this will have to be an asynchronous function.- Додатково, ви можете надати
timeout
(у мілісекундах), щоб вказати, як довго чекати кожного рядка перед перериванням. Примітка: за замовчуванням тайм-аут становить 5 секунд.
Example:
test.concurrent.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', async ({a, b, expected}) => {
expect(a + b).toBe(expected);
});
test.concurrent.only.each(table)(name, fn)
Also under the alias: it.concurrent.only.each(table)(name, fn)
Use test.concurrent.only.each
if you want to only run specific tests with different test data concurrently.
test.concurrent.only.each
is available with two APIs:
test.concurrent.only.each(table)(name, fn)
test.concurrent.only.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', async (a, b, expected) => {
expect(a + b).toBe(expected);
});
test('will not be run', () => {
expect(1 / 0).toBe(Infinity);
});
test.only.each`table`(name, fn)
test.concurrent.only.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', async ({a, b, expected}) => {
expect(a + b).toBe(expected);
});
test('will not be run', () => {
expect(1 / 0).toBe(Infinity);
});
test.concurrent.skip.each(table)(name, fn)
Also under the alias: it.concurrent.skip.each(table)(name, fn)
Use test.concurrent.skip.each
if you want to stop running a collection of asynchronous data driven tests.
test.concurrent.skip.each
is available with two APIs:
test.concurrent.skip.each(table)(name, fn)
test.concurrent.skip.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', async (a, b, expected) => {
expect(a + b).toBe(expected); // will not be run
});
test('will be run', () => {
expect(1 / 0).toBe(Infinity);
});
test.concurrent.skip.each`table`(name, fn)
test.concurrent.skip.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', async ({a, b, expected}) => {
expect(a + b).toBe(expected); // will not be run
});
test('will be run', () => {
expect(1 / 0).toBe(Infinity);
});
test.each(table)(name, fn, timeout)
Also under the alias: it.each(table)(name, fn)
and it.each`table`(name, fn)
Use test.each
if you keep duplicating the same test with different data. test.each
allows you to write the test once and pass data in.
test.each
is available with two APIs:
1. test.each(table)(name, fn, timeout)
table
:Array
of Arrays with the arguments that are passed into the testfn
for each row.- Примітка якщо ви передасте в плаский масив примітивів, внутрішньо вона буде змаплена в таблицю
[1, 2, 3] -> [[1], [2], [3]]
- Примітка якщо ви передасте в плаский масив примітивів, внутрішньо вона буде змаплена в таблицю
назва
:Рядок
the title of the test block.- Генеруйте унікальні заголовки тестів за допомогою позиційних вбудованих параметрів за допомогою
printf
formatting:%p
- pretty-format.%s
- Рядок (String).%d
- Число (Number).%i
- Ціле число (Integer).%f
- Число з плаваючою комою (Floating point value).%j
- JSON.%o
- Об'єкт (Object).%#
- Index of the test case.%%
- single percent sign ('%'). Це не розглядається як аргумент.
- Або ж генеруйте унікальні заголовки тестів шляхом впровадження властивостей об'єкту теста за допомогою
$variable
- To inject nested object values use you can supply a keyPath i.e.
$variable.path.to.value
- Ви можете використати
$#
для додавання індексу тесту - You cannot use
$variable
with theprintf
formatting except for%%
- To inject nested object values use you can supply a keyPath i.e.
- Генеруйте унікальні заголовки тестів за допомогою позиційних вбудованих параметрів за допомогою
fn
:Function
the test to be run, this is the function that will receive the parameters in each row as function arguments.- Додатково, ви можете надати
timeout
(у мілісекундах), щоб вказати, як довго чекати кожного рядка перед перериванням. Примітка: за замовчуванням тайм-аут становить 5 секунд.
Example:
test.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', (a, b, expected) => {
expect(a + b).toBe(expected);
});
test.each([
{a: 1, b: 1, expected: 2},
{a: 1, b: 2, expected: 3},
{a: 2, b: 1, expected: 3},
])('.add($a, $b)', ({a, b, expected}) => {
expect(a + b).toBe(expected);
});
2. test.each`table`(name, fn, timeout)
table
:Tagged Template Literal
- First row of variable name column headings separated with
|
- One or more subsequent rows of data supplied as template literal expressions using
${value}
syntax.
- First row of variable name column headings separated with
назва
:Рядок
the title of the test, use$variable
to inject test data into the test title from the tagged template expressions.- To inject nested object values use you can supply a keyPath i.e.
$variable.path.to.value
- To inject nested object values use you can supply a keyPath i.e.
fn
:Function
the test to be run, this is the function that will receive the test data object.- Додатково, ви можете надати
timeout
(у мілісекундах), щоб вказати, як довго чекати кожного рядка перед перериванням. Примітка: за замовчуванням тайм-аут становить 5 секунд.
Example:
test.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', ({a, b, expected}) => {
expect(a + b).toBe(expected);
});
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.
Додатково, ви можете вказати timeout
(у мілісекундах) на те як довго чекати перед перериванням. Примітка: за замовчуванням тайм-аут становить 5 секунд.
Наприклад, нехай у вас є наступні тести:
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.only.each(table)(name, fn)
Also under the aliases: it.only.each(table)(name, fn)
, fit.each(table)(name, fn)
, it.only.each`table`(name, fn)
and fit.each`table`(name, fn)
Use test.only.each
if you want to only run specific tests with different test data.
test.only.each
is available with two APIs:
test.only.each(table)(name, fn)
test.only.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', (a, b, expected) => {
expect(a + b).toBe(expected);
});
test('will not be run', () => {
expect(1 / 0).toBe(Infinity);
});
test.only.each`table`(name, fn)
test.only.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', ({a, b, expected}) => {
expect(a + b).toBe(expected);
});
test('will not be run', () => {
expect(1 / 0).toBe(Infinity);
});
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.
test.skip.each(table)(name, fn)
Also under the aliases: it.skip.each(table)(name, fn)
, xit.each(table)(name, fn)
, xtest.each(table)(name, fn)
, it.skip.each`table`(name, fn)
, xit.each`table`(name, fn)
and xtest.each`table`(name, fn)
Use test.skip.each
if you want to stop running a collection of data driven tests.
test.skip.each
is available with two APIs:
test.skip.each(table)(name, fn)
test.skip.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', (a, b, expected) => {
expect(a + b).toBe(expected); // will not be run
});
test('will be run', () => {
expect(1 / 0).toBe(Infinity);
});
test.skip.each`table`(name, fn)
test.skip.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', ({a, b, expected}) => {
expect(a + b).toBe(expected); // will not be run
});
test('will be run', () => {
expect(1 / 0).toBe(Infinity);
});
test.todo(name)
Also under the alias: it.todo(name)
Use test.todo
when you are planning on writing tests. These tests will be highlighted in the summary output at the end so you know how many tests you still need todo.
Note: If you supply a test callback function then the test.todo
will throw an error. If you have already implemented the test and it is broken and you do not want it to run, then use test.skip
instead.
API
name
:String
the title of the test plan.
Example:
const add = (a, b) => a + b;
test.todo('add should be associative');