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

More than 1 year has passed since last update.

テストでモックを使用したら"ReferenceError: Cannot access 'mockGetAllRecords' before initialization"のエラーが出た。

Posted at

はじめに

現在学習記録アプリのテストを書いているのですが、モックを使用した際に出たエラーの解決方法をまとめます。

問題

getAllRecordsとdeleteRecordsの2つの関数をモック化したのですが、 "ReferenceError: Cannot access 'mockGetAllRecords' before initialization" のエラーが出ました。
モック関数が初期化される前にアクセスしようとしてしまっているようです。

tsx
//モック化
const mockGetAllRecords = jest
.fn()
.mockResolvedValue([ new Record("1", "テスト", 3, "2024-03-16 09:30:48.200885")]  )

const mockDeleteRecords = jest
.fn()
.mockResolvedValue([]);

jest.mock("../utils/supabaseFunctions", () => {
    return{
        getAllRecords:mockGetAllRecords,
        deleteRecords:mockDeleteRecords,
    }});

解決方法

getAllRecords:mockGetAllRecordsgetAllRecords:()=>mockGetAllRecords()と修正したらエラーが消えました。

tsx
//モック化
const mockGetAllRecords = jest
.fn()
.mockResolvedValue([ new Record("1", "テスト", 3, "2024-03-16 09:30:48.200885")]  )

const mockDeleteRecords = jest
.fn()
.mockResolvedValue([]);

//修正
jest.mock("../utils/supabaseFunctions", () => {
    return{
        getAllRecords:()=>mockGetAllRecords(),
        deleteRecords: () => mockDeleteRecords(),
    }});

おわりに

なぜエラーが消えたのか、具体的な理由は謎です。。

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