LoginSignup
1
0

More than 1 year has passed since last update.

Jestでスナップショットのパスを変更する

Last updated at Posted at 2021-03-03

ちょっと面倒だったのでメモ

サンプル

TypeScriptをdistにコンパイルして、.jsファイルでテストを実行する場合でサンプルを書きますが、
別のパターンでも簡単に応用できると思います。

ファイル構造は以下の想定

src/
  ├─ index.ts
  ├─ index.test.ts // テスト
  └─ index.test.snap <= ここにスナップショットを出力したい
dist/
  └─ src/
      ├─ index.js
      └─ index.test.js

実行コマンドの想定

jest dist/src/index.test.js

実装

jest.config.js
module.exports = {
  ...
  snapshotResolver: './src/snapshotResolver.js',
};
src/snapshotResolver.js
module.exports = {
  /**
   * テストファイルのパス => スナップショットのファイルパスに変換
   * dist/src/index.test.js
   * => src/index.test.snap
   */
  resolveSnapshotPath: ( testPath, snapshotExtension ) =>
    testPath.replace( 'dist/', '' ).replace( '.js', '' ) + snapshotExtension,

  /**
   * スナップショットのファイルパス => テストのファイルパスの変換
   * src/index.test.snap
   * => dist/src/test/create.test.js
   */
  resolveTestPath: ( snapshotFilePath, snapshotExtension ) =>
    snapshotFilePath
      .replace( 'src/', 'dist/src/' )
      .slice( 0, -snapshotExtension.length ) + '.js',

  /**
   * 整合性の確認のためのサンプルが必須のようです
   */
  testPathForConsistencyCheck: 'dist/src/example.test.js',
};

以上!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0