はじめに
初めて、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に初めて触るので、沼りっぱなしです。