本文へスキップ
Typle
ログイン状態を確認中

プログラミング · Jest · テスト

Jest構文のタイピング練習

Jest 30 のテストの書き方67個を、初級・上級の2つのリストで打って覚えます。test・describe・expect、test.skip、beforeEach などのフックを、コードの形で練習できます。

2リスト・67語

無料・ログインなしで練習できます。押すとこのパックをフォローし、すぐに練習が始まります。

収録している言葉

Jest構文(初級)

打つ言葉意味・補足
// Jest 30 / JavaScript・TypeScript対象環境:例の前提(TypeScriptの実行には適切な変換設定が必要。型検査は別途実施。断片中の対象関数・変数は実装または準備する)
test.skip('未対応', () => {});test.skip:一時的に実行対象外(放置しない)
test.only('調査中', () => {});test.only:このテストに限定(コミット前に解除。CIでは禁止設定等を検討)
test.todo('負数を扱う');test.todo:未実装のテストを記録(テストを実装・検証したことにはならない)
beforeEach(() => { jest.clearAllMocks(); });beforeEach:各テスト前に初期化(スコープ内の各テストが対象)
afterEach(() => { jest.restoreAllMocks(); });afterEach:各テスト後に後片付け(spyOn等で差し替えたものを復元)
expect(1 + 2).toBe(3);toBe:Object.is相当の比較(オブジェクト内容の比較はtoEqual等)
expect([1, 2]).toStrictEqual([1, 2]);toStrictEqual:型等も含めた厳密な深い比較
expect(1).not.toBe(2);not:否定
expect('value').toBeDefined();toBeDefined:undefinedでないこと(nullは通る)
expect('hello').toBeTruthy(); expect(0).toBeFalsy();toBeTruthy / toBeFalsy:真偽値変換後の判定(true/false自体を検証するならtoBe)
expect(0.1 + 0.2).toBeCloseTo(0.3, 5);toBeCloseTo:浮動小数点の近似比較(第2引数は小数桁精度)
expect('Hello Pomo').toMatch(/Pomo/);toMatch:文字列・正規表現
expect(['A', 'B']).toContain('A');toContain:要素を含む(要素の同一性比較)
expect([{ id: 1 }]).toContainEqual({ id: 1 });toContainEqual:内容が等しい要素を含む
expect([1, 2]).toHaveLength(2);toHaveLength:長さ
await expect(Promise.resolve(42)).resolves.toBe(42);resolves:Promise成功値を検証(必ずawaitまたはreturn)
expect.hasAssertions(); expect(true).toBe(true);expect.hasAssertions:最低1回の検証を要求
expect({ id: 1, name: 'Pomo' }).toMatchSnapshot();toMatchSnapshot:保存済み結果と比較(生成・更新した差分をレビュー。意図的な期待値の代わりに乱用しない)
expect('hello').toMatchInlineSnapshot('"hello"');toMatchInlineSnapshot:期待値をソース内に保存(変更時は差分を確認)
const fn = jest.fn();jest.fn:モック関数を作成
const fn = jest.fn((n: number) => n * 2);mockImplementation:実装を置き換える(TypeScriptの例)
jest.clearAllMocks();mockClear / clearAllMocks:呼出履歴をクリア(設定したモック実装は残る)
jest.resetAllMocks();mockReset / resetAllMocks:履歴と実装をリセット(戻り値等の実装も消える)
jest.restoreAllMocks();mockRestore / restoreAllMocks:元の実装を復元(主にspyOn等。任意のjest.fn代入を自動復元するものではない)
const mockedApi = jest.mocked(api);jest.mocked:モック型として扱う(型補助。実装自体をモック化する処理ではない。apiを準備する)
await jest.advanceTimersByTimeAsync(1000);advanceTimersByTimeAsync:Promise処理も考慮して時間を進める(modern fake timers有効時。legacy fake timersでは利用不可)
jest.runOnlyPendingTimers();runOnlyPendingTimers:現在の保留タイマーを実行(fake timers有効時。再帰タイマーのrunAllTimers等には注意)
export default { testEnvironment: 'jsdom' };jsdom:DOMに近いテスト環境(jest-environment-jsdomを別途導入。実ブラウザーではない)
npx jestjest CLI:テスト実行(ターミナルで実行)
npx jest --watch--watch / --coverage:監視実行・カバレッジ(カバレッジ率だけでテストの質は判断しない)
npx jest --coverage--watch / --coverage:監視実行・カバレッジ(カバレッジ率だけでテストの質は判断しない)
npx jest --runInBand--runInBand / -t:直列実行・名前で絞る
npx jest -t '足し算'--runInBand / -t:直列実行・名前で絞る

Jest構文(上級)

打つ言葉意味・補足
import { describe, test, expect, jest, beforeEach, afterEach, beforeAll, afterAll } from '@jest/globals';@jest/globals:テストAPIをimport(通常はグローバルでも利用可能。ESMではjestを明示import)
test('足し算', () => { expect(1 + 2).toBe(3); });test / it:テストを定義(itはtestの別名)
describe('add', () => { test('正の数', () => expect(1 + 2).toBe(3)); });describe:テストを分類(describe自体で非同期処理を待たない)
test.each([[1, 2, 3], [2, 3, 5]])('%i + %i = %i', (a, b, expected) => { expect(a + b).toBe(expected); });test.each:表形式のパラメーターテスト
beforeAll(async () => { await setup(); }); afterAll(async () => { await teardown(); });beforeAll / afterAll:一度だけ準備・終了(setup・teardownを用意。Promiseを返すかawait)
test.concurrent('独立した処理', async () => { expect(await Promise.resolve(1)).toBe(1); });test.concurrent:テストを並行実行(共有変数・DB・モック等の状態競合に注意)
expect({ name: 'Pomo' }).toEqual({ name: 'Pomo' });toEqual:内容の深い比較(undefinedプロパティ等の厳密さはtoStrictEqualと異なる)
expect(null).toBeNull(); expect(undefined).toBeUndefined();toBeNull / toBeUndefined:null・undefinedの判定
expect(10).toBeGreaterThan(5); expect(1).toBeLessThan(5);toBeGreaterThan / toBeLessThan:大小(以上・以下はOrEqual付き)
expect({ user: { name: 'Pomo' } }).toHaveProperty('user.name', 'Pomo');toHaveProperty:プロパティと値
expect({ id: 1, name: 'Pomo' }).toMatchObject({ id: 1 });toMatchObject:オブジェクトの部分一致
expect({ id: 1, name: 'Pomo' }).toEqual(expect.objectContaining({ id: 1 })); expect([1, 2, 3]).toEqual(expect.arrayContaining([2]));objectContaining / arrayContaining:非対称の部分一致(arrayContainingは順序・完全一致を要求しない)
expect({ id: 1 }).toEqual({ id: expect.any(Number) }); expect('x').toEqual(expect.anything());expect.any / anything:型・値の大まかな検証(anythingはnullとundefinedを除く)
expect(() => { throw new Error('失敗'); }).toThrow('失敗');toThrow:同期例外(実行結果ではなく関数を渡す)
test('取得', async () => { const value = await Promise.resolve(42); expect(value).toBe(42); });async / await:非同期処理を待って検証(await・return漏れは検証前にテスト終了し得る)
await expect(Promise.reject(new Error('失敗'))).rejects.toThrow('失敗');rejects:Promise失敗を検証(必ずawaitまたはreturn)
test('非同期', async () => { expect.assertions(1); await expect(Promise.resolve(42)).resolves.toBe(42); });expect.assertions:アサーション実行数
const fn = jest.fn().mockReturnValue(42); expect(fn()).toBe(42);mockReturnValue:固定の戻り値
const fn = jest.fn().mockReturnValueOnce('first').mockReturnValue('later');mockReturnValueOnce:次の1回の戻り値
const fn = jest.fn<() => Promise<number>>().mockResolvedValue(42);mockResolvedValue:成功するPromise(このジェネリクス例はTypeScript)
const fn = jest.fn<() => Promise<never>>().mockRejectedValue(new Error('失敗'));mockRejectedValue:失敗するPromise(TypeScriptの例)
const spy = jest.spyOn(console, 'log').mockImplementation(() => {}); console.log('Hello'); expect(spy).toHaveBeenCalledWith('Hello'); spy.mockRestore();jest.spyOn:既存メソッドを監視(spyOn単体では通常元の実装も呼ぶ)
const fn = jest.fn(); fn(); expect(fn).toHaveBeenCalled();toHaveBeenCalled:呼ばれたことを検証
const fn = jest.fn(); fn(); expect(fn).toHaveBeenCalledTimes(1);toHaveBeenCalledTimes:呼出回数
const fn = jest.fn(); fn('Pomo'); expect(fn).toHaveBeenCalledWith('Pomo');toHaveBeenCalledWith:呼出引数
const fn = jest.fn(); fn('first'); expect(fn).toHaveBeenNthCalledWith(1, 'first');toHaveBeenNthCalledWith:指定回の引数
const fn = jest.fn((n: number) => n * 2); fn(3); expect(fn.mock.calls[0]).toEqual([3]); expect(fn.mock.results[0].value).toBe(6);mock.calls / mock.results:呼出履歴・結果を確認(TypeScriptの例)
jest.mock('./api', () => ({ fetchUser: jest.fn() }));jest.mock:モジュールをモック(CommonJSまたは対応する変換環境の例。native ESMでは別手順)
jest.unstable_mockModule('./api.js', () => ({ fetchUser: jest.fn() })); const api = await import('./api.js');unstable_mockModule:native ESMモック(実験的API。対象・利用側のimport順とESM実行設定が重要)
beforeEach(() => { jest.useFakeTimers(); }); afterEach(() => { jest.useRealTimers(); });useFakeTimers / useRealTimers:仮想タイマーと復元(実タイマーへ必ず戻す)
jest.useFakeTimers(); const fn = jest.fn(); setTimeout(fn, 1000); jest.advanceTimersByTime(1000); expect(fn).toHaveBeenCalled(); jest.useRealTimers();advanceTimersByTime:時間を進める
jest.useFakeTimers(); jest.setSystemTime(new Date('2026-01-01T00:00:00Z')); expect(new Date().getUTCFullYear()).toBe(2026); jest.useRealTimers();setSystemTime:システム時刻を固定(時刻変更だけではタイマーを自動発火しない)
export default { testEnvironment: 'node', clearMocks: true, restoreMocks: true };jest.config:設定ファイル(ESM設定例。TypeScript変換等は別途)

ほかの公式パックを見る