🛠️

ts-jestを使ってnode_modules内のESMを読み込めるように設定する

2022/12/04に公開

はじめに

Firebaseのパッケージに依存しているコードのテストコードを書いていて、Firebaseに関するモジュールをモック化しようとしたところ、以下のシンタックスエラーが発生しました。

● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

Details:

省略/node_modules/firebase/auth/dist/index.esm.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export * from '@firebase/auth';
                                                                                      ^^^^^^

Firebase のパッケージが ESM形式になっていて、exportの部分でJestがパースできずにエラーになってしまったようです。

Jestのコード変換について

JestのESM(ECMAScript Modules)対応はまだ実験的サポートの段階でデフォルトでは未対応のようでした。サポート外の構文の場合は変換する必要があり、transform のオプションも用意されています。transformer のプラグインにはデフォルトで babel-jest が入っているようです。そしてESM対応の設定も以下のページ記載があります。

https://jestjs.io/ja/docs/ecmascript-modules

https://jestjs.io/ja/docs/code-transformation#writing-custom-transformers

今回のケースでは元々 ts-jest を使用しており、 ts-jestのほうではESM対応がされていましたのでそちらを使用しました。

https://kulshekhar.github.io/ts-jest/docs/guides/esm-support/

やったこと

一旦パッケージを最新化

"@types/jest": "^29.2.3",
"jest": "^29.3.1",
"ts-jest": "^29.0.3",

jest.config.js の修正

ESM Support を参考に jest.config.js を修正しました。
ポイントになった部分は以下の項目です。

preset

プリセットがいくつか用意されています。今回はts-jest/presets/js-with-ts-esmを指定しました。

https://kulshekhar.github.io/ts-jest/docs/getting-started/presets/

ちなみにプリセットの具体的な内容はテストコードを見るとわかいやすいかもしれないです。

presets.spec.ts#L39-L44

 expect(presets.jsWithTsESM).toEqual({
    extensionsToTreatAsEsm: [...JS_EXT_TO_TREAT_AS_ESM, ...TS_EXT_TO_TREAT_AS_ESM],
    transform: {
      '^.+\\.m?[tj]sx?$': ['ts-jest', { useESM: true }],
    },
  })

transform

https://kulshekhar.github.io/ts-jest/docs/getting-started/options

ここに ts-jest の設定を記述します。プリセットを使っているので、プリセットにないものだけを書いています。

transform: {
    "^.+\\.m?[tj]sx?$": [
      "ts-jest",
      {
        tsconfig: "<rootDir>/tsconfig.test.json",
      },
    ],
  },

ちなみにglobalsというオプションは deprecated になっていました。
https://github.com/kulshekhar/ts-jest/blob/main/CHANGELOG.md#deprecations

ts-jest[ts-jest-transformer] (WARN) Define `ts-jest` config under `globals` is deprecated. Please do
transform: {
    <transform_regex>: ['ts-jest', { /* ts-jest config goes here in Jest */ }],
},

transformIgnorePatterns

https://jestjs.io/ja/docs/configuration#transformignorepatterns-arraystring

これはJestの変換対象から除外するためのオプションです。
デフォルトではnode_modulesが除外する対象になっています。

Default: ["/node_modules/", "\\.pnp\\.[^\\\/]+$"]

今回 Firebase のパッケージは変換対象に含めたいので下記のように指定しました。

transformIgnorePatterns: ["node_modules/(?!(firebase|@firebase))"],

最終的な設定内容

最終的には以下のような感じになりました。

jest.config.js
module.exports = {
  preset: "ts-jest/presets/js-with-ts-esm",
  setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
  roots: ["<rootDir>/src"],
  testEnvironment: "jsdom",
  moduleFileExtensions: ["ts", "tsx", "js"],
  testPathIgnorePatterns: [省略],
  moduleNameMapper: {省略},
  testPathIgnorePatterns: [省略],
  transform: {
    "^.+\\.m?[tj]sx?$": [
      "ts-jest",
      {
        tsconfig: "<rootDir>/tsconfig.test.json",
      },
    ],
  },
  transformIgnorePatterns: ["node_modules/(?!(firebase|@firebase))"],
};

さいごに

以上でFirebaseのESMモジュールが読み込めるようになり、モック化できるようになりました。

Discussion