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でモック作成したのに、DBに実通信していた話

Posted at

状況

Jestによるテスト中、本来モック化したはずのSupabase関数が実際にDBに通信してしまい、タイムアウトエラーが発生した。

エラー内容

.bash
console.error
FetchError: request to https:/***supabaseのAPI***/?select=* failed, reason: Socket connection timeout

環境

  • React + Vite
  • Supabase
  • Jest + React Testing Library

原因:モックの記述

.js
jest.mock("../utils/SupaBaseFunctions.js", () => {
  getAllStudyRecords: jest.fn().mockResolvedValue({ data: [], error: null }),
  insertStudyRecords: jest.fn(),
});

jest.mock("~", () => {/**省略**/})と書いてしまい、ただ関数ブロックとして書いてあり何も return できていない。undefinedが返る。

解決

.js
jest.mock("../utils/SupaBaseFunctions.js", () => ({
  getAllStudyRecords: jest.fn().mockResolvedValue({ data: [], error: null }),
  insertStudyRecords: jest.fn().mockResolvedValue(undefined),
  deleteStudyRecordsById: jest.fn().mockResolvedValue(undefined),
}));

jest.mock("~", () => ({/**省略**/}))と修正。これにより{}をreturnする。(returnの省略記法)

補足:mockResolvedValue()を使う理由

モック化した関数は(getAllStudyRecordsなど)は非同期関数。
そのため、jest.fn()だけではundefinedを返してしまい、awaitでの処理に失敗。
→よって、mockResolvedValue()を使う。

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?