INDEX
真偽値
toBe(value)
厳密な等価性(===)をチェックします。オブジェクトの参照が同じであることを確認します。
test('Matchers examples', () => {
const value = 25;
// toBe
expect(value).toBe(25);
});
toEqual(value)
深い等価性をチェックします。オブジェクトや配列の内容が等しいかどうかを確認します。
test('Matchers examples', () => {
const obj = { name: 'Jest', type: 'Testing Framework' };
// toEqual
expect(obj).toEqual({ name: 'Jest', type: 'Testing Framework' });
});
- toBeとtoEqualの違い
上記の例では、
obj1
とobj2
は異なるオブジェクトですが、その内容は同じなのでtoEqual
はパスします。しかし、toBe
を使用するとテストは失敗します。test('toBe vs toEqual', () => { const obj1 = { a: 1, b: 2 }; const obj2 = { a: 1, b: 2 }; expect(obj1).toBe(obj2); // 失敗 });
not
マッチャーの否定を行います。例えば、expect(value).not.toBe(4)はvalueが4でないことを確認します。
test('Matchers examples', () => {
const value = 25;
// not
expect(value).not.toBe(24);
});
toBeNull()
値がnullであることを確認します。
test('Matchers examples', () => {
// toBeNull
expect(null).toBeNull();
});
toBeUndefined()
値がundefinedであることを確認します。
test('Matchers examples', () => {
// toBeUndefined
expect(undefined).toBeUndefined();
});
toBeDefined()
値がundefinedでないことを確認します。
test('Matchers examples', () => {
const value = 25;
// toBeDefined
expect(value).toBeDefined();
});
toBeTruthy()
値が真偽値のコンテキストでtrueと評価されることを確認します。
test('Matchers examples', () => {
const value = 25;
// toBeTruthy
expect(value).toBeTruthy();
});
toBeFalsy()
値が真偽値のコンテキストでfalseと評価されることを確認します。
test('Matchers examples', () => {
// toBeFalsy
expect(null).toBeFalsy();
});
数値
toBeGreaterThan(number) / toBeGreaterThanOrEqual(number)
toBeGreaterThan: 期待値が引数より大きいことをチェックします toBeGreaterThanOrEqual: 期待値が引数以上であることをチェックします。
test('Matchers examples', () => {
const value = 10;
// toBeGreaterThan
expect(value).toBeGreaterThan(9);
// toBeGreaterThanOrEqual
expect(value).toBeGreaterThanOrEqual(10);
});
toBeLessThan(number) / toBeLessThanOrEqual(number)
toBeLessThan: 期待値が引数より小さいことをチェックします。 toBeLessThanOrEqual: 期待値が引数以下であることをチェックします。
test('Matchers examples', () => {
const value = 10;
// toBeLessThan
expect(value).toBeLessThan(11);
// toBeLessThanOrEqual
expect(value).toBeLessThanOrEqual(10);
});
浮動小数点数
toBeCloseTo(number, precision?)
浮動小数点数の比較を行います。精度はオプションで指定できます。
test('Matchers examples', () => {
// toBeCloseTo
expect(0.23 + 0.1).toBeCloseTo(0.33);
});
文字列 / 配列
toMatch(regexp | string)
文字列が正規表現または文字列にマッチすることを確認します。
test('Matchers examples', () => {
const str = 'Hello Jest';
// toMatch
expect(str).toMatch(/Jest/);
});
toContain(item)
配列または文字列が特定のアイテムを含むことを確認します。
test('Matchers examples', () => {
const arr = ['Jest', 'Jasmine', 'Mocha'];
// toContain
expect(arr).toContain('Jest');
});
toHaveLength(number)
配列や文字列の長さを確認します
test('Matchers examples', () => {
const arr = ['Jest', 'Jasmine', 'Mocha'];
// toHaveLength
expect(arr).toHaveLength(3);
});
例外処理
toThrow(error?)
関数が特定のエラーをスローすることを確認します。
test('Matchers examples', () => {
// toThrow
expect(() => { throw new Error('Error!'); }).toThrow('Error!');
});