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 element(s) given to waitForElementToBeRemoved are already removed. waitForElementToBeRemoved requires that the element(s) exist(s) before waiting for removal.

Posted at

はじめに

Jestでテストコードを書いているときに数十分の間、右往左往したので投稿します。

環境

  • Jest 30.2.0
  • React 19.2.0
  • Vite 7.2.4

問題

下記は、リストのアイテム内の削除ボタンを押すと、Supabaseに削除クエリを発行して、そのアイテムがリストから削除されていることをテストするコードです。

Top.spec.jsx
const recordItem2 = studyRecords[1];
await userEvent.click(within(studyRecords[1]).getByRole('button', { name: '削除' }));
await waitForElementToBeRemoved(recordItem2);

このコードを実行した所、タイトルのエラーが発生しました。

解決方法

screen.debugで確認した所、waitForElementToBeRemovedを実行した段階で削除されているみたいでした。
これは、jest.mockでsupabaseの処理をモック化していて、Promiseを返すようにしていたのですが、遅延がないために起こったようです。
そのため、

Top.spec.jsx
jest.mock('../utils/supabase/supabaseStudyRecord', () => ({
  fetchAllStudyRecords: jest.fn(() => Promise.resolve(mockRecordsInfo.data)),
  insertStudyRecord: jest.fn((obj) => Promise.resolve({ id: ++mockRecordsInfo.id, ...obj })),
  deleteStudyRecord: jest.fn(() => Promise.resolve(null)),
}));

Top.spec.jsx
jest.mock('../utils/supabase/supabaseStudyRecord', () => ({
  fetchAllStudyRecords: jest.fn(() => new Promise((resolve) => setTimeout(() => resolve(mockRecordsInfo.data), 200))),
  insertStudyRecord: jest.fn(
    (obj) => new Promise((resolve) => setTimeout(() => resolve({ id: ++mockRecordsInfo.id, ...obj }), 200))
  ),
  deleteStudyRecord: jest.fn(() => new Promise((resolve) => setTimeout(() => resolve(null), 200))),
}));

に変更した所、エラーが消えました。

おわりに

モック周りの理解をもっと深めていきたいです。

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?