メインコンテンツへスキップ
バージョン: 29.7

マッチャーの使い方

非公式ベータ版翻訳

このページは PageTurner AI で翻訳されました(ベータ版)。プロジェクト公式の承認はありません。 エラーを見つけましたか? 問題を報告 →

Jestでは「マッチャー」を使ってさまざまな方法で値をテストできます。このドキュメントでは一般的に使われるマッチャーを紹介します。すべてのマッチャーについてはexpect APIドキュメントをご覧ください。

一般的なマッチャー

最もシンプルな値のテスト方法は厳密な等価性による比較です。

test('two plus two is four', () => {
expect(2 + 2).toBe(4);
});

このコードでは、expect(2 + 2)が「expectation(期待値)」オブジェクトを返します。通常このオブジェクトに対してはマッチャーを呼び出す以外の操作は行いません。ここでは.toBe(4)がマッチャーです。Jestは実行時に失敗したマッチャーをすべて追跡し、分かりやすいエラーメッセージを表示します。

toBeObject.isを使用して厳密な等価性をテストします。オブジェクトの値をチェックしたい場合はtoEqualを使用してください:

test('object assignment', () => {
const data = {one: 1};
data['two'] = 2;
expect(data).toEqual({one: 1, two: 2});
});

toEqualはオブジェクトや配列のすべてのフィールドを再帰的にチェックします。

ヒント

toEqualundefinedプロパティを持つオブジェクトキー、undefinedの配列要素、配列のスパース性、オブジェクト型の不一致を無視します。これらを考慮するには代わりにtoStrictEqualを使用してください。

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);
}
}
});

真偽値の扱い

テストではundefinednullfalseを区別する必要がある場合と、区別したくない場合があります。Jestには明確な意図を表現できるヘルパーが用意されています。

  • toBeNullnull のみにマッチ

  • toBeUndefinedundefined のみにマッチ

  • toBeDefinedtoBeUndefined の逆

  • toBeTruthyif 文で真と扱われるものすべてにマッチ

  • toBeFalsyif 文で偽と扱われるものすべてにマッチ

例:

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);
});

浮動小数点の等価性チェックにはtoEqualではなくtoBeCloseToを使用してください。わずかな丸め誤差にテストが依存するのを防げます。

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.
});

文字列

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/);
});

配列と反復可能オブジェクト

toContainで配列や反復可能オブジェクトに特定のアイテムが含まれているかをチェックできます:

const shoppingList = [
'diapers',
'kleenex',
'trash bags',
'paper towels',
'milk',
];

test('the shopping list has milk on it', () => {
expect(shoppingList).toContain('milk');
expect(new Set(shoppingList)).toContain('milk');
});

例外

特定の関数が呼び出されたときにエラーをスローするかテストしたい場合はtoThrowを使用します。

function compileAndroidCode() {
throw new Error('you are using the wrong JDK!');
}

test('compiling android goes as expected', () => {
expect(() => compileAndroidCode()).toThrow();
expect(() => compileAndroidCode()).toThrow(Error);

// You can also use a string that must be contained in the error message or a regexp
expect(() => compileAndroidCode()).toThrow('you are using the wrong JDK');
expect(() => compileAndroidCode()).toThrow(/JDK/);

// Or you can match an exact error message using a regexp like below
expect(() => compileAndroidCode()).toThrow(/^you are using the wrong JDK$/); // Test fails
expect(() => compileAndroidCode()).toThrow(/^you are using the wrong JDK!$/); // Test pass
});
ヒント

例外をスローする関数はラップ関数内で呼び出す必要があります。そうしないとtoThrowアサーションは失敗します。

その他の機能

これはほんの一部です。すべてのマッチャーについてはリファレンスドキュメントを参照してください。

利用可能なマッチャーについて学んだら、次はJestで非同期コードをテストする方法を確認すると良いでしょう。