1
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でモック化しても読み込まれないエラーの解決方法について

Posted at

はじめに

Jestでモック化をしていてiconメソッドが見つからないというエラーが表示され、こちらの解決方法について記事にします。

TypeError: Cannot read properties of undefined (reading 'icon')
const greenIcon = L.icon({


【修正前のコード】
.tsx
jest.mock('leaflet', () => ({
  icon: jest.fn()
}));

解決方法

Jestの公式に書いてありました。

~以下公式内容~

デフォルトのエクスポートのES6モジュールで factory パラメータを使用する場合、 __esModule: true プロパティを指定する必要があります。
通常、このプロパティは Babel / TypeScript によって生成されますが、ここでは手動で設定する必要があります。
デフォルトエクスポートをインポートする場合、エクスポートオブジェクトから default という名前のプロパティをインポートします。

leafletのLオブジェクトはデフォルトエクスポートしていました。

import L from 'leaflet';
.tsx

jest.mock('leaflet', () => ({
  __esModule: true,
  default: {
    icon: jest.fn()
  }
}));

参考

ファクトリーパラメータとは第2引数の () => ({}) のこと(ファクトリーメソッドとは違います)

おわりに

用語1つ1つの意味もついでに調べていくと理解が深まります


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