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

SyntaxError: Cannot use import statement outside a module

Posted at

はじめに

Next.jsでJestの環境を構築をしている際にエラーが出たので記事にしておきます。

問題

Next.js上でJestの環境構築後テストを実行すると以下のエラーが出る。

SyntaxError: Cannot use import statement outside a module

解決策

jest.config.ts内のコードをデフォルトのものではなく、Next.jsの公式ドキュメントのものにするとなおりました。

jest.config.ts
import type {Config} from 'jest';

const config: Config = {
   clearMocks: true,
   collectCoverage: true,
   coverageDirectory: "coverage",
   coverageProvider: "v8",
   testEnvironment: "jsdom",
   setupFilesAfterEnv: ['<rootDir>/jest.setup.ts']
 };

export default config;

以下のようにします⬇️

jest.config.ts
import type { Config } from 'jest'
import nextJest from 'next/jest.js'

const createJestConfig = nextJest({
  // 次のパスをあなたのNext.jsアプリに指定して、テスト環境でnext.config.jsと.envファイルを読み込みます
  dir: './',
})

// Jestに渡されるカスタム設定を追加します
const config: Config = {
  coverageProvider: 'v8',
  testEnvironment: 'jsdom',
  // 各テストが実行される前に、さらに設定オプションを追加します
  setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
}

// createJestConfigは、非同期であるnext/jestがNext.jsの設定を読み込めるように、この方法でエクスポートされます
export default createJestConfig(config)

おわりに

公式ドキュメント通り上からやるのが大事ですね。

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?