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?

【Jest】 The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables

1
Last updated at Posted at 2026-02-01

はじめに

初めて、React + Jestでテストを作成していて、jest.mockでモックを作成しているときに発生したエラーです。

問題

supabaseの処理のモックを作成しようとして下記のコードを記述したところ、表題のエラーが発生しました。

beforeEach(() => {
    let id = 0;
    jest.mock('../utils/supabase/supabaseStudyRecord.js', () => ({
      fetchAllStudyRecords: jest.fn(),
      insertStudyRecord: jest.fn((obj) => ({ id: ++id, ...obj })),
      deleteStudyRecord: jest.fn(),
    }));
});

解決方法

ドキュメントによると、

Since calls to jest.mock() are hoisted to the top of the file, Jest prevents access to out-of-scope variables. By default, you cannot first define a variable and then use it in the factory. Jest will disable this check for variables that start with the word mock. However, it is still up to you to guarantee that they will be initialized on time. Be aware of Temporal Dead Zone.

と記述されており、ファクトリー関数では、スコープ外の変数にアクセスできない模様です。
ただし、 mock という接頭辞をつけた変数はスコープ外の変数でもアクセスできるようです。また、jest.mockはトップレベルのスコープでないと、うまく動作しない模様です。

そのため、下記のコードに変更するとエラーが消えました。

// トップレベルのスコープ
let mockId = 0;
jest.mock('../utils/supabase/supabaseStudyRecord.js', () => ({
  fetchAllStudyRecords: jest.fn(),
  insertStudyRecord: jest.fn((obj) => ({ id: ++mockId, ...obj })),
  deleteStudyRecord: jest.fn(),
}));

おわりに

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?