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?

【Vitest】「ReferenceError: Cannot access 'error' before initialization」の解決方法

1
Posted at

はじめに

next.jsでアプリを作っていて、vitestでテストを書いていたところエラーが発生しました。

問題

ReferenceError: Cannot access 'error' before initialization

【エラーが発生したコード】

let error = null;

vi.mock("@/hooks/useAuth", async () => {
  const actual = await vi.importActual("@/hooks/useAuth");
  return {
    ...actual,
    signInWithPassword: vi.fn().mockResolvedValue({
      error: error,
    }),
  };
});

解決方法

vi.mock("@/hooks/useAuth", async () => {
  const actual = await vi.importActual("@/hooks/useAuth");
  return {
    ...actual,
    signInWithPassword: vi.fn().mockResolvedValue({
      error: null,
    }),
  };
});

変数を挟まずに直接errorにnullを指定しました。
ホイスティングと言って、Vitestが vi.mock() の呼び出しをファイルの先頭に自動的に巻き上げるため、let error = null の宣言より前に実行されるのが原因です。

おわりに

テストによってsupabaseが返却してくるerrorを変更したかったのですが、別の方法を考えてみます。

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?