1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Babelを使ってJestでESMを読み込めるようにする

Posted at

はじめに

Jestでテスト実行時にESMを読み込めるようにBabelの設定を行いました。

Babel設定

Babelをインストール

npm install --save-dev @babel/preset-env babel-jest

babel.config.jsを作成

js
module.exports = {
  presets: [
    ["next/babel"],  // Next.jsのコードを変換
    [
      "@babel/preset-env",
      {
        targets: {
          node: "current",
        },
      },
    ],
    "@babel/preset-typescript",  // TypeScriptのコードを変換
  ],
};

jest.config.tsに設定を追加

ts
import type { Config } from "jest";
import nextJest from "next/jest.js";

const createJestConfig = nextJest({
  dir: "./",
});

const config: Config = {
  preset: "ts-jest/presets/default-esm",  // TypeScriptとESMを使う設定
  globals: {
    "ts-jest": {
      tsconfig: "tsconfig.json",
      useESM: true,
    },
  },
  coverageProvider: "v8",
  testEnvironment: "jsdom",
  transform: {
    "^.+\\.(ts|tsx|js|jsx)$": "babel-jest",  // Babelでコードを変換
  },
};

export default createJestConfig(config);

参考

1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?