Matcherを使用する
Jest では、マッチャー ("matcher") を使用して、様々な方法で値のテストをすることができます。 このドキュメン トでは、よく使われるマッチャーをいくつか紹介します。 For the full list, see the expect API doc.
一般的なマッチャー
値をテストする最も簡単な方法は、厳密に等価であることです。
test('two plus two is four', () => {
expect(2 + 2).toBe(4);
});
In this code, expect(2 + 2) returns an "expectation" object. マッチャーを利用しなければこれらの "expectation" オブジェクトは大きな効果を発揮しません。 In this code, .toBe(4) is the matcher. Jestが実行されると、失敗したマッチャーをすべて追跡し、素晴らしいエラーメッセージを表示することができます。
toBe uses Object.is to test exact equality. If you want to check the value of an object, use toEqual:
test('object assignment', () => {
const data = {one: 1};
data['two'] = 2;
expect(data).toEqual({one: 1, two: 2});
});
toEqual recursively checks every field of an object or array.
toEqual ignores object keys with undefined properties, undefined array items, array sparseness, or object type mismatch. To take these into account use toStrictEqual instead.
You can also test for the opposite of a matcher using not:
test('adding positive numbers is not zero', () => {
for (let a = 1; a < 10; a++) {
for (let b = 1; b < 10; b++) {
expect(a + b).not.toBe(0);
}
}
});
真偽値(およびそれらしく思える値)
In tests, you sometimes need to distinguish between undefined, null, and false, but you sometimes do not want to treat these differently. Jestには、(それらのケースで) 求められるものを明確に実装したヘルパーが備わっています。
toBeNullmatches onlynulltoBeUndefinedmatches onlyundefinedtoBeDefinedis the opposite oftoBeUndefinedtoBeTruthymatches anything that anifstatement treats as truetoBeFalsymatches anything that anifstatement treats as false
例:
test('null', () => {
const n = null;
expect(n).toBeNull();
expect(n).toBeDefined();
expect(n).not.toBeUndefined();
expect(n).not.toBeTruthy();
expect(n).toBeFalsy();
});
test('zero', () => {
const z = 0;
expect(z).not.toBeNull();
expect(z).toBeDefined();
expect(z).not.toBeUndefined();
expect(z).not.toBeTruthy();
expect(z).toBeFalsy();
});
あなたは、あなたのコードがしたいことに最も正確に対応するマッチャーを使うべきです。
数値
数値の比較するほとんどの方法について、対応するマッチャーがあります。
test('two plus two', () => {
const value = 2 + 2;
expect(value).toBeGreaterThan(3);
expect(value).toBeGreaterThanOrEqual(3.5);
expect(value).toBeLessThan(5);
expect(value).toBeLessThanOrEqual(4.5);
// toBe and toEqual are equivalent for numbers
expect(value).toBe(4);
expect(value).toEqual(4);
});
For floating point equality, use toBeCloseTo instead of toEqual, because you don't want a test to depend on a tiny rounding error.
test('adding floating point numbers', () => {
const value = 0.1 + 0.2;
//expect(value).toBe(0.3); This won't work because of rounding error
expect(value).toBeCloseTo(0.3); // This works.
});
文字列
You can check strings against regular expressions with toMatch:
test('there is no I in team', () => {
expect('team').not.toMatch(/I/);
});
test('but there is a "stop" in Christoph', () => {
expect('Christoph').toMatch(/stop/);
});