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?

【備忘録】モックデータで削除処理のテストコードを書く

Posted at

やりたいこと

モックデータをセットした状態で、削除処理が実行出来るかテストコードを書きたい

実装

App.spec.tsx
// 本番データはここのgetAllReocrds関数で取得してくる
import * as api from "../../utils/supabaseFunction";

jest.mock("../../utils/supabaseFunction");

describe("App", () => {
  test("削除ができること", async () => {
    // 初回データ
    // getAllRecordsで取得するデータをモックデータに置き換える
    (api.getAllRecords as jest.Mock)
    .mockResolvedValueOnce([
      { id: 1, title: "てすと", time: "333" },
      { id: 2, title: "てすと2", time: "444" },
    ]);

    // 削除処理
    // deleteRecordでモックデータを削除する
    (api.deleteRecord as jest.Mock).mockResolvedValue({});

    // 削除後データ(1番の要素がなくなる)
    (api.getAllRecords as jest.Mock)
      .mockResolvedValueOnce([
        { id: 2, title: "てすと2", time: "444" }
      ]);

    render(<App />);

    // 初期データの表示を待つ
    const deleteBtn = await screen.findByTestId("delete-button-1");
    expect(deleteBtn).toBeInTheDocument();

    // 削除ボタンをクリック
    await userEvent.click(deleteBtn);

    // 更新後の表示を確認
    const items = await screen.findAllByTestId("item");
    expect(items).toHaveLength(1);
    expect(items[0]).toHaveTextContent("てすと2");
  });
App.tsx
{records.map((item) => {
  return (
    <div key={item.id}>
      <p data-testid="item">{item.title}:{item.time}</p>
      <button 
        onClick={() => handleDelete(item.id)} 
        data-testid={`delete-button-${item.id}`}>
        ×
      </button>
    </div>
  )
})}

詰まっていたところ

モックデータで削除のテストをする際の流れを理解していなかった。
初期データのモックデータを削除して、それで判定しようとしていた。
削除の関数を別で実行して、エラーが出ていなければモックを削除後のデータに置き換える考えが頭になかった。

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?