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?

src配下にあるファイル参照時に"Cannot find module '@/***' from 'src/***' "のエラーが出る

Posted at

はじめに

next.js×TypeScriptで作成したアプリに対して、Jestでテスト実行したところ、下記のようなエラーが出ました。

  Cannot find module '@/infra/api' from 'src/__tests__/posts/page.test.tsx'

原因

Jest側でsrc配下のフォルダが正しく認識されていないようでした。
従って、Jestの設定を修正していきます。

解決方法

1.Jest.config.tsに設定を追加

moduleDirectoriesはデフォルトだと"node_modules"ですが、ここに "src"を追加します
そうすることでJestがsrc/を基準にモジュールを探してくれます

Jest.config.ts
const config: Config = {

  moduleDirectories: ["node_modules", "src"], // 追加
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/$1",
  }
};

2.tsconfig.jsonに設定を追加

compilerOptionspaths["*"]から ["./*"]に修正し、"baseUrl": "src"を追加します。

両者の違いは下記です。

["*"]プロジェクトルート (/) 直下を基準に解釈する
["./*"]baseUrl (src) を基準に相対パスで解釈する

tsconfig.json
  "compilerOptions": {
  
    "baseUrl": "src",
    "paths": {
      "@/*": ["./*"]
    }
  }

おわりに

Jestの設定ファイルは自動作成されるため、あまり中身を理解できていませんでした。
今回の件で少しだけJestについて詳しくなれたと思います。

参考

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?