影響の大きいライブラリのアップデートを行う際にsnapshotを全てupdateする必要だがPRの差分は一旦小さくするために後でsnapshotテストの更新を行いたいケース等で一部のテストの実行有無を環境変数で切り替えたい時もままある気がするのでやり方をメモ📝
やり方は以下のような関数を用意して、
export const skippableIt = (name: string, test: () => void) => { const skip = process.env.SKIP_TEST === "true"; if (skip) { xit(name, test); } else { it(name, test); } };
以下のようなコードにすると
import { skippableIt } from "../matchers/switchSkipTest"; describe("example", () => { describe("tests", () => { skippableIt("skippable test", () => { expect(1).toBe(1); }); }); });
以下の通り、テストのSkipと実行を環境変数SKIP_TEST
で切り替えることができるようになります 📝
$ SKIP_TEST=true npm run test spec/example.spec.ts PASS spec/example.spec.ts example tests ✓ normal test (1 ms) ○ skipped skippable test Test Suites: 1 passed, 1 total Tests: 1 skipped, 1 passed, 2 total Snapshots: 0 total Time: 1.08 s, estimated 2 s
$ npm run test spec/example.spec.ts FAIL spec/example.spec.ts example tests ✕ skippable test (2 ms) ✓ normal test ● example › tests › skippable test expect(received).toBe(expected) // Object.is equality Expected: 2 Received: 1 4 | describe("tests", () => { 5 | skippableIt("skippable test", () => { > 6 | expect(1).toBe(2); | ^ 7 | }); 8 | 9 | it("normal test", () => { at Object.<anonymous> (spec/example.spec.ts:6:17) at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13) at runJest (node_modules/@jest/core/build/runJest.js:404:19) at _run10000 (node_modules/@jest/core/build/cli/index.js:320:7) at runCLI (node_modules/@jest/core/build/cli/index.js:173:3) Test Suites: 1 failed, 1 total Tests: 1 failed, 1 passed, 2 total Snapshots: 0 total Time: 1.528 s
今回やりたかったこととしてはSnapshotテストの失敗を無視したかったのですが、snapshotテストはカスタムマッチャーで強制的にpassさせてもSnapshotの更新が発生しなかった場合にsnapshot obsolete.
な状態になり、exit code
が1で失敗扱いになってしまい悩んでいたのですが、シンプルに環境変数でit
,xit
の呼び出しをコントロールするのが一番簡単そう(?) 🤔