かもメモ

自分の落ちた落とし穴に何度も落ちる人のメモ帳

Jest + Enzyme config で adapter を自動的に読み込ませたい

React のテストの定番 Jest + Enzyme の構成で、React 16.x 系だと Enzyme の Adapter を読み込ませる必要がり、今までは下記の用な感じで Adapter を読み込ませるファイルを作りテストファイルで都度 import をしていました。

setup.enzyme.js

import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

Enzyme.configure({ adapter: new Adapter() });

xxxx.test.js

import React from 'react';
import './enzyme.setup.js';
import { shallow, mount } from 'enzyme';
...

毎回設定ファイルを import するのが面倒!

Jest の setupFilesAfterEnv 設定を使うと都度 import しなくても済む!

setupFilesAfterEnv
default: []

A list of paths to modules that run some code to configure or set up the testing framework before each test. Since setupFiles executes before the test framework is installed in the environment, this script file presents you the opportunity of running some code immediately after the test framework has been installed in the environment.

If you want a path to be relative to the root directory of your project, please include <rootDir> inside a path's string, like "<rootDir>/a-configs-folder".
cf. Configuring Jest · Jest

setupFilesAfterEnv: [] に渡されたファイルがテスト実行前に読み込まれるみたいです!
ここに Enzyme の Adapter の読み込みをしているファイルのパスを渡せば、テストファイルで都度 import を書く必要がなくなります!!

jest.config.js の設定に追加します

module.exports = {// A list of paths to modules that run some code to configure or set up the testing framework before each test
  setupFilesAfterEnv: [
    '<rootDir>/enzyme.setup.js',
  ],
  …
}

これで、テストファイルは自動的に enzyme.setup.js を読み込むようになりました〜!
オプションサクット読める英語力…切実に必要性を感じてきています…


[参考]

空調のせいか手荒れが酷かったけど、ハンドクリーム導入したらQOL上がりました。(安上がり)