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

[React, Jest] Configuration error:Could not locate module ./App.css mapped as: identity-obj-proxy.

Posted at

はじめに

JestでReactアプリケーションをテスト時に設定エラーが起きたのでまとめます。

問題

下記のファイルをテストすると Could not locate module ./App.css mapped as: identity-obj-proxy.identity-obj-proxy が無いとエラーが出ます。

App.tsx
import "./App.css";

function App() {
  return (
    <>
      <h1>Hello World</h1>
    </>
  );
}

export default App;

jest.config.js ファイルの moduleNameMapper に設定しているのに、インストールが出来てませんでした。

jest.config.js
export default {
  preset: "ts-jest",
  testEnvironment: "jsdom",
  setupFilesAfterEnv: ["./jest.setup.ts"],
  transform: {
    "^.+\\.(ts|tsx)$": "ts-jest",
  },
  moduleNameMapper: {
    "\\.(css|less)$": "identity-obj-proxy",
  },
};

moduleNameMapperとは?
テスト内で特定のモジュールをインポートする際に、代わりに別のモジュールを使用するようにマッピングする設定です

解決方法

identity-obj-proxyをインストールしましょう。

npm i --save-dev identity-obj-proxy

--save-dev は開発環境のみに適用するということ

identity-obj-proxyの役割とは?
通常、CSS や Less ファイルは JavaScript のテスト環境では直接理解できません。identity-obj-proxy は、インポートされた CSS モジュールの各クラス名をそのまま文字列として返すモックオブジェクトを提供します。これにより、コンポーネントが適用するクラス名の存在などをテストできるようになります。

2
1
1

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