Expect
When you're writing tests, you often need to check that values meet certain conditions. expect gives you access to a number of "matchers" that let you validate different things.
For additional Jest matchers maintained by the Jest Community check out jest-extended.
Методи
expect(value)expect.extend(matchers)expect.anything()expect.any(constructor)expect.arrayContaining(array)expect.assertions(number)expect.hasAssertions()expect.objectContaining(object)expect.stringContaining(string)expect.stringMatching(string | regexp)expect.addSnapshotSerializer(serializer).not.resolves.rejects.toBe(value).toHaveBeenCalled().toHaveBeenCalledTimes(number).toHaveBeenCalledWith(arg1, arg2, ...).toHaveBeenLastCalledWith(arg1, arg2, ...).nthCalledWith(nthCall, arg1, arg2, ....).toHaveLength(number).toHaveProperty(keyPath, value?).toBeCloseTo(number, numDigits?).toBeDefined().toBeFalsy().toBeGreaterThan(number).toBeGreaterThanOrEqual(number).toBeLessThan(number).toBeLessThanOrEqual(number).toBeInstanceOf(Class).toBeNull().toBeTruthy().toBeUndefined().toBeNaN().toContain(item).toContainEqual(item).toEqual(value).toMatch(regexp | string).toMatchObject(object).toMatchSnapshot(propertyMatchers?, hint?).toThrow(error?).toThrowErrorMatchingSnapshot(hint?)
Довідка
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 повинне бути значення, яке генерує ваш код, а аргументом для матчера повинне бути правильне значення. Якщо ви їх переплутаєте місцями, то ваші тести працюватимуть, але повідомлння про помилки в тестах будуть виглядати дуже дивно.
expect.extend(matchers)
Ви можете використовувати expect.extend щоб додати ваші власні матчери для Jest. For example, let's say that you're testing a number utility library and you're frequently asserting that numbers appear within particular ranges of other numbers. You could abstract that into a toBeWithinRange matcher:
expect.extend({
toBeWithinRange(received, floor, ceiling) {
const pass = received >= floor && received <= ceiling;
if (pass) {
return {
message: () =>
`expected ${received} not to be within range ${floor} - ${ceiling}`,
pass: true,
};
} else {
return {
message: () =>
`expected ${received} to be within range ${floor} - ${ceiling}`,
pass: false,
};
}
},
});
test('numeric ranges', () => {
expect(100).toBeWithinRange(90, 110);
expect(101).not.toBeWithinRange(0, 100);
expect({apples: 6, bananas: 3}).toEqual({
apples: expect.toBeWithinRange(1, 10),
bananas: expect.not.toBeWithinRange(11, 20),
});
});
Note: In TypeScript, when using @types/jest for example, you can declare the new toBeWithinRange matcher like this:
declare global {
namespace jest {
interface Matchers<R> {
toBeWithinRange(a: number, b: number): R;
}
}
}
Custom Matchers API
Matchers should return an object (or a Promise of an object) with two keys. pass вказує на те, чи було співпадіння, а message надає функцію без аргументів, яка повертає повідомлення про помилку, на випадок невдачі. Таким чином, коли pass має значення false, message повинна повернути повідомлення про помилку, якщо твердження expect(x).yourMatcher() не виконується. А коли pass має значення true, message повинна повернути повідомленя про помилку, якщо не виконується твердження expect(x).not.yourMatcher().
Matchers are called with the argument passed to expect(x) followed by the arguments passed to .yourMatcher(y, z):
expect.extend({
yourMatcher(x, y, z) {
return {
pass: true,
message: () => '',
};
},
});
These helper functions and properties can be found on this inside a custom matcher:
this.isNot
A boolean to let you know this matcher was called with the negated .not modifier allowing you to display a clear and correct matcher hint (see example code).
this.promise
A string allowing you to display a clear and correct matcher hint:
'rejects'if matcher was called with the promise.rejectsmodifier'resolves'if matcher was called with the promise.resolvesmodifier''if matcher was not called with a promise modifier
this.equals(a, b)
Це функція глибокого порівняння, яка повертає true, якщо два об’єкти мають те саме значення (рекурсивно).
this.expand
A boolean to let you know this matcher was called with an expand option. When Jest is called with the --expand flag, this.expand can be used to determine if Jest is expected to show full diffs and errors.
this.utils
Існує багато корисних інструментів, доступних через this.utils, які, в основному, складаються з функцій, які експортуються в пакеті jest-matcher-utils.
Найбільш корисні з них - це matcherHint, printExpected і printReceived для форматування повідомлень про помилки. Наприклад, ось як це реалізовано для матчера toBe:
const diff = require('jest-diff');
expect.extend({
toBe(received, expected) {
const options = {
comment: 'Object.is equality',
isNot: this.isNot,
promise: this.promise,
};
const pass = Object.is(received, expected);
const message = pass
? () =>
this.utils.matcherHint('toBe', undefined, undefined, options) +
'\n\n' +
`Expected: not ${this.utils.printExpected(expected)}\n` +
`Received: ${this.utils.printReceived(received)}`
: () => {
const diffString = diff(expected, received, {
expand: this.expand,
});
return (
this.utils.matcherHint('toBe', undefined, undefined, options) +
'\n\n' +
(diffString && diffString.includes('- Expect')
? `Difference:\n\n${diffString}`
: `Expected: ${this.utils.printExpected(expected)}\n` +
`Received: ${this.utils.printReceived(received)}`)
);
};
return {actual: received, message, pass};
},
});
Виведеться щось таке:
expect(received).toBe(expected)
Expected value to be (using Object.is):
"banana"
Received:
"apple"
Коли твердження не виконується, повідомлення про помилку повинне давати користувачеві якомога більше інформації, щоб він міг швидко вирішити проблему. Варто робити точні і зрозумілі поідомлення про помилки, щоб переконатися, що б ваші власні матчери були зручні у використанні.
expect.anything()
expect.anything() відповідає будь-якому значенню, окрім null та undefined. Ви можете використовувати його всередині toEqual чи toBeCalledWith замість явного вказання значень. Наприклад, якщо ви хочете перевірити, що мок функція була викликана з аргументом, не рівним null:
test('map calls its argument with a non-null argument', () => {
const mock = jest.fn();
[1].map(x => mock(x));
expect(mock).toBeCalledWith(expect.anything());
});
expect.any(constructor)
expect.any(constructor) перевіряє, що значення було створене з допомогою заданого конструктора. Ви можете використовувати його всередині toEqual чи toBeCalledWith замість явного вказання значень. Наприклад, якщо ви хочете перевірити, що мок функція була викликана з аргументом типу Number:
function randocall(fn) {
return fn(Math.floor(Math.random() * 6 + 1));
}
test('randocall calls its callback with a number', () => {
const mock = jest.fn();
randocall(mock);
expect(mock).toBeCalledWith(expect.any(Number));
});
expect.arrayContaining(array)
expect.arrayContaining(array) перевіряє, чи отриманий масив містить всі елементи очікуваного. Іншими словами, що очікуваний масив є підмножиною отриманого. Отже, отриманий масив може містити елементи, яких немає в очікуваному.
Ви можете використовувати його замість явного вказання значень:
- в
toEqualабоtoBeCalledWith - щоб вказати відповідність властивості в
objectContainingабоtoMatchObject
describe('arrayContaining', () => {
const expected = ['Alice', 'Bob'];
it('matches even if received contains additional elements', () => {
expect(['Alice', 'Bob', 'Eve']).toEqual(expect.arrayContaining(expected));
});
it('does not match if received does not contain expected elements', () => {
expect(['Bob', 'Eve']).not.toEqual(expect.arrayContaining(expected));
});
});
describe('Beware of a misunderstanding! A sequence of dice rolls', () => {
const expected = [1, 2, 3, 4, 5, 6];
it('matches even with an unexpected number 7', () => {
expect([4, 1, 6, 7, 3, 5, 2, 5, 4, 6]).toEqual(
expect.arrayContaining(expected),
);
});
it('does not match without an expected number 2', () => {
expect([4, 1, 6, 7, 3, 5, 7, 5, 4, 6]).not.toEqual(
expect.arrayContaining(expected),
);
});
});
expect.assertions(number)
expect.assertions(number) перевіряє, що певна кількість тверджень було викликано в межах тесту. Це часто буває корисним при тестуванні асинхронного коду, щоб переконатися, що твердження в зворотніх викликах було викликано.
Наприклад, нехай у нас є функція doAsync, яка приймає два зворотні виклики callback1 і callback2 і асинхронно викликає їх в невідомому порядку. Ми можемо протестувати це так:
test('doAsync calls both callbacks', () => {
expect.assertions(2);
function callback1(data) {
expect(data).toBeTruthy();
}
function callback2(data) {
expect(data).toBeTruthy();
}
doAsync(callback1, callback2);
});
Виклик expect.assertions(2) перевіряє, що обидва зворотні виклики дійсно були викликані.
expect.hasAssertions()
expect.hasAssertions() перевіряє, що хоча б одне твердження було викликане в межах тесту. Це часто буває корисним при тестуванні асинхронного коду, щоб переконатися, що твердження в зворотніх викликах було викликано.
Наприклад, нехай у нас є кілька функцій, які працюють з якимось спільним станом. prepareState викликає функцію зворотнього виклику з об’єктом стану, validateState виконує над цим об’єктом якусь операцію, а waitOnState повертає проміс, який очікує поки виконається зворотній виклик prepareState. Ми можемо протестувати це так:
test('prepareState prepares a valid state', () => {
expect.hasAssertions();
prepareState(state => {
expect(validateState(state)).toBeTruthy();
});
return waitOnState();
});
Виклик expect.hasAssertions() перевіряє, що зворотній виклик prepareState дійсно було викликано.
expect.objectContaining(object)
expect.objectContaining(object) відповідає будь-якому об’єкту, який рекурсивно відповідає очікуваному. Іншими словами, що очікуваний об’єкт є підмножиною отриманого. Therefore, it matches a received object which contains properties that are present in the expected object.
Замість значень властивостей в очікуваному об’єкті ви можете використовувати матчери типу expect.anything() та інші.
Наприклад, нехай ми очікуємо, що функція onPress буде викликана з об’єктом Event і нам потрібно перевірити, що цей об’єкт має властивості event.x і event.y. Ми можемо зробити це так:
test('onPress gets called with the right thing', () => {
const onPress = jest.fn();
simulatePresses(onPress);
expect(onPress).toBeCalledWith(
expect.objectContaining({
x: expect.any(Number),
y: expect.any(Number),
}),
);
});
expect.stringContaining(string)
expect.stringContaining(string) matches the received value if it is a string that contains the exact expected string.
expect.stringMatching(string | regexp)
expect.stringMatching(string | regexp) matches the received value if it is a string that matches the expected string or regular expression.
Ви можете використовувати його замість явного вказання значень:
- в
toEqualабоtoBeCalledWith - щоб вказати відповідність елементу в
arrayContaining - щоб вказати відповідність властивості в
objectContainingабоtoMatchObject
Наступний приклад показує як можна використовувати кілька вкладених матчерів з expect.stringMatching всередині expect.arrayContaining.
describe('stringMatching in arrayContaining', () => {
const expected = [
expect.stringMatching(/^Alic/),
expect.stringMatching(/^[BR]ob/),
];
it('matches even if received contains additional elements', () => {
expect(['Alicia', 'Roberto', 'Evelina']).toEqual(
expect.arrayContaining(expected),
);
});
it('does not match if received does not contain expected elements', () => {
expect(['Roberto', 'Evelina']).not.toEqual(
expect.arrayContaining(expected),
);
});
});
expect.addSnapshotSerializer(serializer)
Ви можете викликати expect.addSnapshotSerializer, щоб додати модуль, який форматує специфічні для вашої програми структури даних.
Для откремого файлу з тестами, вказаний модуль буде мати пріорітет над модулями з розділу snapshotSerializers файла конфігурації, які мають пріорітет над серіалізаторами для вбудованих типів JavaScript та React елементів. Останній доданий модуль буде використаний першим.
import serializer from 'my-serializer-module';
expect.addSnapshotSerializer(serializer);
// впливає на всі твердження expect(value).toMatchSnapshot() в межах файла з тестами
If you add a snapshot serializer in individual test files instead of adding it to snapshotSerializers configuration:
- Ви робити залежність явною, замість неявної.
- Ви уникаєте обмежень на зміну конфігурації, які можуть призвести до необхідності виконувати команду
ejectдля create-react-app.
Для додаткової інформації звертайтеся до розділу налаштування Jest.
.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');
});
Note that, since you are still testing promises, the test is still asynchronous. 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',
);
});
Note that, since you are still testing promises, the test is still asynchronous. Hence, you will need to tell Jest to wait by returning the unwrapped assertion.
Alternatively, you can use async/await in combination with .rejects.
test('rejects to octopus', async () => {
await expect(Promise.reject(new Error('octopus'))).rejects.toThrow('octopus');
});
.toBe(value)
Use .toBe to compare primitive values or to check referential identity of object instances. It calls Object.is to compare values, which is even better for testing than === strict equality operator.
Наприклад, наступний код буде валідувати деякі властивості об’єкту can:
const can = {
name: 'pamplemousse',
ounces: 12,
};
describe('the can', () => {
test('has 12 ounces', () => {
expect(can.ounces).toBe(12);
});
test('has a sophisticated name', () => {
expect(can.name).toBe('pamplemousse');
});
});
Don't use .toBe with floating-point numbers. Наприклад, через округлення в JavaScript, 0.2 + 0.1 не дорівнює 0.3. Якщо вам потрібно перевіряти числа з плаваючою комою, використовуйте .toBeCloseTo.
Although the .toBe matcher checks referential identity, it reports a deep comparison of values if the assertion fails. If differences between properties do not help you to understand why a test fails, especially if the report is large, then you might move the comparison into the expect function. For example, to assert whether or not elements are the same instance:
- rewrite
expect(received).toBe(expected)asexpect(Object.is(received, expected)).toBe(true) - rewrite
expect(received).not.toBe(expected)asexpect(Object.is(received, expected)).toBe(false)
.toHaveBeenCalled()
Також має псевдонім .toBeCalled()
Використовуйте .toHaveBeenCalled, щоб переконатися, що мок функція була викликана.
For example, let's say you have a drinkAll(drink, flavour) function that takes a drink function and applies it to all available beverages. You might want to check that drink gets called for 'lemon', but not for 'octopus', because 'octopus' flavour is really weird and why would anything be octopus-flavoured? Це можна зробити наступним чином:
function drinkAll(callback, flavour) {
if (flavour !== 'octopus') {
callback(flavour);
}
}
describe('drinkAll', () => {
test('drinks something lemon-flavoured', () => {
const drink = jest.fn();
drinkAll(drink, 'lemon');
expect(drink).toHaveBeenCalled();
});
test('does not drink something octopus-flavoured', () => {
const drink = jest.fn();
drinkAll(drink, 'octopus');
expect(drink).not.toHaveBeenCalled();
});
});
.toHaveBeenCalledTimes(number)
Використовуйте .toHaveBeenCalledTimes, щоб переконатися, що мок функція була викликана певну кількість разів.
Наприклад, нехай у вас є функція drinkEach(drink, Array<flavor>), яка приймає функцію drink та викликає її для масиву переданих напоїв. Ви можете захотіти перевірити, що передана функція була викликана рівно вказану кількість разів. Це можна зробити наступним чином:
test('drinkEach drinks each drink', () => {
const drink = jest.fn();
drinkEach(drink, ['lemon', 'octopus']);
expect(drink).toHaveBeenCalledTimes(2);
});
.toHaveBeenCalledWith(arg1, arg2, ...)
Також має псевдонім .toBeCalledWith()
Використовуйте .toHaveBeenCalledWith(), щоб переконатися, що мок функція була викликана зі вказаними аргументами.
Наприклад, нехай ви можете зареєструвати напій з допомогою функції register(), а функція applyToAll(f) повинна застосувати функцію f до всіх зареєстрованих напоїв. Щоб переконатися, що це працює, ви можете написати:
test('registration applies correctly to orange La Croix', () => {
const beverage = new LaCroix('orange');
register(beverage);
const f = jest.fn();
applyToAll(f);
expect(f).toHaveBeenCalledWith(beverage);
});
.toHaveBeenLastCalledWith(arg1, arg2, ...)
Також має псевдонім .lastCalledWith(arg1, arg2, ...)
Ви можете використати .toHaveBeenLastCalledWith, щоб перевірити аргументи, з якими мок функція була викликана востаннє. Наприклад, нехай у вас є функція applyToAllFlavors(f), яка застосовує функцію f до набору смаків і ви хочете переконатися, що коли ви її викличите, то останній смак, з яким вона буде працювати - це 'mango'. Ви можете написати:
test('applying to all flavors does mango last', () => {
const drink = jest.fn();
applyToAllFlavors(drink);
expect(drink).toHaveBeenLastCalledWith('mango');
});
.nthCalledWith(nthCall, arg1, arg2, ....)
If you have a mock function, you can use .nthCalledWith to test what arguments it was nth called with. For example, let's say you have a drinkEach(drink, Array<flavor>) function that applies f to a bunch of flavors, and you want to ensure that when you call it, the first flavor it operates on is 'lemon' and the second one is 'octopus'. Ви можете написати:
test('drinkEach drinks each drink', () => {
const drink = jest.fn();
drinkEach(drink, ['lemon', 'octopus']);
expect(drink).nthCalledWith(1, 'lemon');
expect(drink).nthCalledWith(2, 'octopus');
});
Note: the nth argument must be positive integer starting from 1.
.toHaveLength(number)
Використовуйте .toHaveLength, щоб перевірити, що об’єкт має властивість .length і вона дорівнює певному числовому значенню.
Це особливо корисно для перевірки розміру масивів або довжини рядків.
expect([1, 2, 3]).toHaveLength(3);
expect('abc').toHaveLength(3);
expect('').not.toHaveLength(5);
.toHaveProperty(keyPath, value?)
Використовуйте .toHaveProperty, щоб перевірити, чи властивість за заданим в keyPath посиланням існує для об’єкта. For checking deeply nested properties in an object you may use dot notation or an array containing the keyPath for deep references.
You can provide an optional value argument to compare the received property value (recursively for all properties of object instances, also known as deep equality, like the toEqual matcher).
Наступий приклад містить об’єкт houseForSale з двома вкладеними властивостями. We are using toHaveProperty to check for the existence and values of various properties in the object.
// Object containing house features to be tested
const houseForSale = {
bath: true,
bedrooms: 4,
kitchen: {
amenities: ['oven', 'stove', 'washer'],
area: 20,
wallColor: 'white',
},
};
test('this house has my desired features', () => {
// Example Referencing
expect(houseForSale).toHaveProperty('bath');
expect(houseForSale).toHaveProperty('bedrooms', 4);
expect(houseForSale).not.toHaveProperty('pool');
// Deep referencing using dot notation
expect(houseForSale).toHaveProperty('kitchen.area', 20);
expect(houseForSale).toHaveProperty('kitchen.amenities', [
'oven',
'stove',
'washer',
]);
expect(houseForSale).not.toHaveProperty('kitchen.open');
// Deep referencing using an array containing the keyPath
expect(houseForSale).toHaveProperty(['kitchen', 'area'], 20);
expect(houseForSale).toHaveProperty(
['kitchen', 'amenities'],
['oven', 'stove', 'washer'],
);
expect(houseForSale).toHaveProperty(['kitchen', 'amenities', 0], 'oven');
expect(houseForSale).not.toHaveProperty(['kitchen', 'open']);
});
.toBeCloseTo(number, numDigits?)
Use toBeCloseTo to compare floating point numbers for approximate equality.
The optional numDigits argument limits the number of digits to check after the decimal point. For the default value 2, the test criterion is Math.abs(expected - received) < 0.005 (that is, 10 ** -2 / 2).
Intuitive equality comparisons often fail, because arithmetic on decimal (base 10) values often have rounding errors in limited precision binary (base 2) representation. For example, this test fails:
test('adding works sanely with decimals', () => {
expect(0.2 + 0.1).toBe(0.3); // Fails!
});
It fails because in JavaScript, 0.2 + 0.1 is actually 0.30000000000000004.
For example, this test passes with a precision of 5 digits:
test('adding works sanely with decimals', () => {
expect(0.2 + 0.1).toBeCloseTo(0.3, 5);
});
.toBeDefined()
Висористовуйте .toBeDefined(), щоб переірити, що змінна визначена. For example, if you want to check that a function fetchNewFlavorIdea() returns something, you can write:
test('there is a new flavor idea', () => {
expect(fetchNewFlavorIdea()).toBeDefined();
});
Ви також можете написати expect(fetchNewFlavorIdea()).not.toBe(undefined), але хорошою практикою є уникати прямого використання undefined в коді.
.toBeFalsy()
Use .toBeFalsy when you don't care what a value is and you want to ensure a value is false in a boolean context. For example, let's say you have some application code that looks like:
drinkSomeLaCroix();
if (!getErrors()) {
drinkMoreLaCroix();
}
Вас може не цікавити, яке саме значення повертає getErrors. Це може бути false, null чи 0 — ваш код все одно буде працювати. Отже, якщо в ихочете перевірити, що немає помилок після вживання Ла-Круа, ви можете написати:
test('drinking La Croix does not lead to errors', () => {
drinkSomeLaCroix();
expect(getErrors()).toBeFalsy();
});
In JavaScript, there are six falsy values: false, 0, '', null, undefined, and NaN. Everything else is truthy.
.toBeGreaterThan(number)
Use toBeGreaterThan to compare received > expected for numbers. For example, test that ouncesPerCan() returns a value of more than 10 ounces:
test('ounces per can is more than 10', () => {
expect(ouncesPerCan()).toBeGreaterThan(10);
});
.toBeGreaterThanOrEqual(number)
Use toBeGreaterThanOrEqual to compare received >= expected for numbers. For example, test that ouncesPerCan() returns a value of at least 12 ounces:
test('ounces per can is at least 12', () => {
expect(ouncesPerCan()).toBeGreaterThanOrEqual(12);
});
.toBeLessThan(number)
Use toBeLessThan to compare received < expected for numbers. For example, test that ouncesPerCan() returns a value of less than 20 ounces:
test('ounces per can is less than 20', () => {
expect(ouncesPerCan()).toBeLessThan(20);
});
.toBeLessThanOrEqual(number)
Use toBeLessThanOrEqual to compare received <= expected for numbers. For example, test that ouncesPerCan() returns a value of at most 12 ounces:
test('ounces per can is at most 12', () => {
expect(ouncesPerCan()).toBeLessThanOrEqual(12);
});
.toBeInstanceOf(Class)
Use .toBeInstanceOf(Class) to check that an object is an instance of a class. This matcher uses instanceof underneath.
class A {}
expect(new A()).toBeInstanceOf(A);
expect(() => {}).toBeInstanceOf(Function);
expect(new A()).toBeInstanceOf(Function); // помилка
.toBeNull()
.toBeNull() is the same as .toBe(null) but the error messages are a bit nicer. So use .toBeNull() when you want to check that something is null.
function bloop() {
return null;
}
test('bloop returns null', () => {
expect(bloop()).toBeNull();
});
.toBeTruthy()
Use .toBeTruthy when you don't care what a value is and you want to ensure a value is true in a boolean context. For example, let's say you have some application code that looks like:
drinkSomeLaCroix();
if (thirstInfo()) {
drinkMoreLaCroix();
}
Вас може не цікавити, яке саме значення повертає thirstInfo. Це може бути true або складний об’єкт — ваш код все одно буде працювати. So if you want to test that thirstInfo will be truthy after drinking some La Croix, you could write:
test('drinking La Croix leads to having thirst info', () => {
drinkSomeLaCroix();
expect(thirstInfo()).toBeTruthy();
});
In JavaScript, there are six falsy values: false, 0, '', null, undefined, and NaN. Everything else is truthy.
.toBeUndefined()
Висористовуйте .toBeUndefined(), щоб переірити, що змінна не визначена. Наприклад, якщо ви хочете перевірити, що функція bestDrinkForFlavor(flavor) повертає undefined, якщо їй передати смак 'octopus':
test('the best drink for octopus flavor is undefined', () => {
expect(bestDrinkForFlavor('octopus')).toBeUndefined();
});
Ви також можете написати expect(bestDrinkForFlavor()).toBe(undefined), але хорошою практикою є уникати прямого використання undefined в коді.
.toBeNaN()
Use .toBeNaN when checking a value is NaN.
test('passes when value is NaN', () => {
expect(NaN).toBeNaN();
expect(1).not.toBeNaN();
});
.toContain(item)
Use .toContain when you want to check that an item is in an array. For testing the items in the array, this uses ===, a strict equality check. .toContain can also check whether a string is a substring of another string.
For example, if getAllFlavors() returns an array of flavors and you want to be sure that lime is in there, you can write:
test('the flavor list contains lime', () => {
expect(getAllFlavors()).toContain('lime');
});
.toContainEqual(item)
Use .toContainEqual when you want to check that an item with a specific structure and values is contained in an array. For testing the items in the array, this matcher recursively checks the equality of all fields, rather than checking for object identity.
describe('my beverage', () => {
test('is delicious and not sour', () => {
const myBeverage = {delicious: true, sour: false};
expect(myBeverages()).toContainEqual(myBeverage);
});
});
.toEqual(value)
Use .toEqual to compare recursively all properties of object instances (also known as "deep" equality). It calls Object.is to compare primitive values, which is even better for testing than === strict equality operator.
For example, .toEqual and .toBe behave differently in this test suite, so all the tests pass:
const can1 = {
flavor: 'grapefruit',
ounces: 12,
};
const can2 = {
flavor: 'grapefruit',
ounces: 12,
};
describe('the La Croix cans on my desk', () => {
test('have all the same properties', () => {
expect(can1).toEqual(can2);
});
test('are not the exact same can', () => {
expect(can1).not.toBe(can2);
});
});
Примітка:
.toEqualне виконує порівняння на глибоку рівність для двох об’єктів помилок. Порівнюються лише їх властивостіmessage. Рекомендується використовувати матчер.toThrowдля тестування об’єктів помилок.
If differences between properties do not help you to understand why a test fails, especially if the report is large, then you might move the comparison into the expect function. For example, use equals method of Buffer class to assert whether or not buffers contain the same content:
- rewrite
expect(received).toEqual(expected)asexpect(received.equals(expected)).toBe(true) - rewrite
expect(received).not.toEqual(expected)asexpect(received.equals(expected)).toBe(false)
.toMatch(regexp | string)
Використовуйте .toMatch, щоб перевірити, що рядок відповідає регулярному виразу.
Наприклад, ви можете не знати точно, що повертає essayOnTheBestFlavor(), але ви знаєте, що це досить довгий рядок і він повинен містити в собі рядок grapefruit. Ви можете протестувати це так:
describe('an essay on the best flavor', () => {
test('mentions grapefruit', () => {
expect(essayOnTheBestFlavor()).toMatch(/grapefruit/);
expect(essayOnTheBestFlavor()).toMatch(new RegExp('grapefruit'));
});
});
Цей матчер також приймає рядок, який він намагатиметься знайти:
describe('grapefruits are healthy', () => {
test('grapefruits are a fruit', () => {
expect('grapefruits').toMatch('fruit');
});
});
.toMatchObject(object)
Використовуйте .toMatchObject, щоб перевірити, що JavaScript об’єкт відповідає підмножині властивостей очікуваного об’єкту. Він відповідає отриманому об’єкту, який місить властивості, яких немає у очікуваному об’єкті.
Ви можете передати масив об’єктів. В такому випадку метод поверне true тільки якщо кожен з об’єктів масиву проходить сходиться (у сенсі toMatchObject, який описаний вище) з відповідним об’єктом очікуваного масиву. Це корисно, якщо в ихочете перевірити, що два масиви збігаються за кількістю елементів на противагу arrayContaining, який дозволяє додаткові елементи в отриманому масиві.
Ви можете поівнювати властивості зі значеннями або з матчерами.
const houseForSale = {
bath: true,
bedrooms: 4,
kitchen: {
amenities: ['oven', 'stove', 'washer'],
area: 20,
wallColor: 'white',
},
};
const desiredHouse = {
bath: true,
kitchen: {
amenities: ['oven', 'stove', 'washer'],
wallColor: expect.stringMatching(/white|yellow/),
},
};
test('the house has my desired features', () => {
expect(houseForSale).toMatchObject(desiredHouse);
});
describe('toMatchObject applied to arrays', () => {
test('the number of elements must match exactly', () => {
expect([{foo: 'bar'}, {baz: 1}]).toMatchObject([{foo: 'bar'}, {baz: 1}]);
});
test('.toMatchObject is called for each elements, so extra object properties are okay', () => {
expect([{foo: 'bar'}, {baz: 1, extra: 'quux'}]).toMatchObject([
{foo: 'bar'},
{baz: 1},
]);
});
});
.toMatchSnapshot(propertyMatchers?, hint?)
This ensures that a value matches the most recent snapshot. Check out the Snapshot Testing guide for more information.
You can provide an optional hint string argument that is appended to the test name. Although Jest always appends a number at the end of a snapshot name, short descriptive hints might be more useful than numbers to differentiate multiple snapshots in a single it or test block. Jest sorts snapshots by name in the corresponding .snap file.
.toThrow(error?)
Also under the alias: .toThrowError(error?)
Використовуйте .toThrow, щоб переконатися, що функція викликає помилку під час виконання. Наприклад, якщо ми хочемо перевірити, що drinkFlavor('octopus') викликає помилку через те, що смак восминога занадто огидний для пиття, ми можемо написати:
test('throws on octopus', () => {
expect(() => {
drinkFlavor('octopus');
}).toThrow();
});
Note: You must wrap the code in a function, otherwise the error will not be caught and the assertion will fail.
You can provide an optional argument to test that a specific error is thrown:
- regular expression: error message matches the pattern
- string: error message includes the substring
- error object: error message is equal to the message property of the object
- error class: error object is instance of class
Наприклад, нехай функція drinkFlavor написана так:
function drinkFlavor(flavor) {
if (flavor == 'octopus') {
throw new DisgustingFlavorError('yuck, octopus flavor');
}
// Робіть інші речі
}
Ми можемо протестувати, що вона викликає помилку кількома способами:
test('throws on octopus', () => {
function drinkOctopus() {
drinkFlavor('octopus');
}
// Test that the error message says "yuck" somewhere: these are equivalent
expect(drinkOctopus).toThrowError(/yuck/);
expect(drinkOctopus).toThrowError('yuck');
// Test the exact error message
expect(drinkOctopus).toThrowError(/^yuck, octopus flavor$/);
expect(drinkOctopus).toThrowError(new Error('yuck, octopus flavor'));
// Test that we get a DisgustingFlavorError
expect(drinkOctopus).toThrowError(DisgustingFlavorError);
});
.toThrowErrorMatchingSnapshot(hint?)
Використовуйте .toThrowErrorMatchingSnapshot, щоб протестувати, що функція викликає помилку під час виконання, яка співпадає з останнім знімком.
You can provide an optional hint string argument that is appended to the test name. Although Jest always appends a number at the end of a snapshot name, short descriptive hints might be more useful than numbers to differentiate multiple snapshots in a single it or test block. Jest sorts snapshots by name in the corresponding .snap file.
Наприклад, нехай у вас є функція drinkFlavor, яка викликає помилку, коли отримує смак 'octopus', і вона написана так:
function drinkFlavor(flavor) {
if (flavor == 'octopus') {
throw new DisgustingFlavorError('yuck, octopus flavor');
}
// Робіть інші речі
}
Тест для цієї функції виглядатиме наступним чином:
test('throws on octopus', () => {
function drinkOctopus() {
drinkFlavor('octopus');
}
expect(drinkOctopus).toThrowErrorMatchingSnapshot();
});
І він створить наступний знімок:
exports[`drinking flavors throws on octopus 1`] = `"yuck, octopus flavor"`;
Ознайомтеся з розділом Тестування дерева React за допомогою знімків для додаткової інформації про тестування зі знімками.