3
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でJestが @/ パスを認識しない問題を解決する方法

Posted at

問題

Next.jsで、以下のように "@/" (パスエイリアス)を使用してインポートしている場合

import { loadJsonData } from '@/app/utils/jsonStorageHandler';

Jestのテストを実行すると次のようなエラーが発生します。

> npx jest

 FAIL  __test__/articles.test.ts
  ● Test suite failed to run                             
    Cannot find module '@/app/utils/jsonStorageHandler' from 'app/api/articles/route.ts'

原因

tsconfig.json
    "paths": {
      "@/*": ["./*"]
    }

TypeScriptやNext.jsはtsconfig.jsonに定義されたパスエイリアス(例えば@/)を自動的に認識してくれますが、Jestはテスト環境で独立して動作するため、これらの設定を自動で引き継がないためです。

したがって、解決策はパスをjestの設定ファイルに追加することです。

解決策

jest.config.js
/** @type {import('ts-jest').JestConfigWithTsJest} **/
module.exports = {
  testEnvironment: "node",
  transform: {
    "^.+.tsx?$": ["ts-jest",{}],
  },
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/$1',  // @/をルートに変換する
  },
};

このようにmoduleNameMapperへパスエイリアスを追加することで、
"@/"によるインポートを使用しているコードもJestでテスト可能になります。

参考

jest.config.jsについて

jest.config.jsへパスエイリアスを追加する

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