0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Next.js + swc/jestでESMのライブラリを使用したコンポーネントのテストに失敗する時の対処法

Posted at

状況

Next.js を使用したアプリケーションのテストで、transformには swc/jest を利用している。
テストコードの中で、 testing-libraryrender()
react-markdown を内部で利用しているコンポーネントをrenderすると、エラーが出てしまう。

    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


    SyntaxError: Unexpected token 'export'

これは react-markdown がESMであることに由来しているようだ。

環境

"@swc/core": "1.4.5",
"@swc/jest": "0.2.36",
"@testing-library/jest-dom": "6.4.2",
"@testing-library/react": "14.2.2",
"jest": "29.7.0",
"typescript": "5.2.2"

対処

https://github.com/vercel/next.js/issues/40183#issuecomment-1979587339
こちらの方法を参考に、 jest.config.js を書き換えることで回避できた :tada:

jest.config.js
const nextJest = require('next/jest')

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

const esModules = [
  'react-markdown',
  'swiper',
  // その他ESMのものを記述
].join('|')

const customJestConfig = {
  cacheDirectory: 'node_modules/.cache/jest',
  moduleNameMapper: {
    '^~/(.*)$': '<rootDir>/src/$1',
    '^@/(.*)$': '<rootDir>/$1',
  },
  testEnvironment: 'jest-environment-jsdom',
  transform: {
    '^.+\\.(t|j)sx?$': [
      '@swc/jest',
      {
        jsc: {
          transform: {
            react: {
              runtime: 'automatic',
            },
          },
        },
      },
    ],
  },
  extensionsToTreatAsEsm: ['.ts', '.tsx'],
  setupFilesAfterEnv: ['./jest.setup.js'],
  // 〜以下略〜
}

module.exports = async () => ({
  ...(await createJestConfig(customJestConfig)()),
  transformIgnorePatterns: [`<rootDir>/node_modules/(?!${esModules})/`],
})

transformIgnorePatterns を createJestConfig()の外側で後から上書きするのがポイントらしい。
https://github.com/vercel/next.js/issues/36077#issuecomment-1096635363

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?