Очікування
Під час написання тестів, часто потрібно перевіряти, чи відповідає з начення певним умовам. Для різноманітних перевірок, expect
надає нам певну кількість "матчерів".
Додаткові матчери Jest, що підтримується спільнотою, шукайте в jest-extended
.
Приклади TypeScript з цієї сторінки будуть працювати, як задокументовано, тільки якщо ви явно імпортуєте Jest API:
import {expect, jest, test} from '@jest/globals';
Інструкцію щодо налаштування Jest за допомогою TypeScript можна знайти на сторінці Початок роботи.
Довідка
- Очікування
- Модифікатори
- Матчери
.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(keyPath, value?)
.toBeCloseTo(number, numDigits?)
.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)
- Асиметричні матчери
expect.anything()
expect.any(constructor)
expect.arrayContaining(array)
expect.not.arrayContaining(array)
expect.arrayOf(value)
expect.not.arrayOf(value)
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)
- Кількість тверджень
- Розширені плагіни
- Serializable properties
Очікування
expect(value)
Функція expect
використовується кожного разу, коли ви хочете перевірити якесь значення. Дуже рідко потрібно викликати expect
саму по собі. Замість цього, ви будете використовувати expect
разом з "матчер" функціями, щоб перевірити твердження щодо якогось значення.
Найпростіше зрозуміти це на прикладі. Уявімо, що у вас є метод bestLaCroixFlavor()
, який повинен повертати рядок 'grapefruit'
. Ось, як ви можете це протестувати:
test('the best flavor is grapefruit', () => {
expect(bestLaCroixFlavor()).toBe('grapefruit');
});
In this case, toBe
is the matcher function. There are a lot of different matcher functions, documented below, to help you test different things.
Аргументом для expect
повинне бути значення, яке генерує ваш код, а аргументом для матчера повинне бути правильне значення. Якщо ви їх переплутаєте місцями, то ваші тести працюватимуть, але повідомлння про помилки в тестах будуть виглядати дуже дивно.
Модифікатори
.not
If you know how to test something, .not
lets you test its opposite. For example, this code tests that the best La Croix flavor is not coconut:
test('the best flavor is not coconut', () => {
expect(bestLaCroixFlavor()).not.toBe('coconut');
});
.resolves
Use resolves
to unwrap the value of a fulfilled promise so any other matcher can be chained. If the promise is rejected the assertion fails.
Наприклад, цей код перевіряє, що проміс виконується успішно і його значення — це 'lemon'
:
test('resolves to lemon', () => {
// не забудьте додати оператор return
return expect(Promise.resolve('lemon')).resolves.toBe('lemon');
});
Оскільки ви все ще тестуєте проміси, тест залишається асинхронним. Hence, you will need to tell Jest to wait by returning the unwrapped assertion.
Крім того, ви можете використовувати async/await
у поєднання з .resolves
:
test('resolves to lemon', async () => {
await expect(Promise.resolve('lemon')).resolves.toBe('lemon');
await expect(Promise.resolve('lemon')).resolves.not.toBe('octopus');
});
.rejects
Use .rejects
to unwrap the reason of a rejected promise so any other matcher can be chained. If the promise is fulfilled the assertion fails.
For example, this code tests that the promise rejects with reason 'octopus'
:
test('rejects to octopus', () => {
// make sure to add a return statement
return expect(Promise.reject(new Error('octopus'))).rejects.toThrow(
'octopus',
);
});