3
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のtoBeDefinedはnullでも通る

3
Posted at

はじめに

Vitestでフロントエンドのテストを作成しているときに、期待通りに動かない場所がありました。

問題

  test("Todoの登録が成功する", async () => {
    render(<App />);
    const user = userEvent.setup();
    const input = await screen.findByPlaceholderText("タイトル");
    await user.type(input, "宿題");
    const button = await screen.findByText("追加");
    await user.click(button);

    const dbError = await screen.queryByText("Failed to add todo");
    expect(dbError).not.toBeDefined();
  });

Todoの登録が成功するとき画面にはエラーメッセージは表示されません。Todoの登録が失敗した時はエラーメッセージが表示されます。
なので、今回は画面上にエラーメッセージが表示されないことを確認したかったのですが、テストが通りませんでした。

解決方法

  test("Todoの登録が成功する", async () => {
    render(<App />);
    const user = userEvent.setup();
    const input = await screen.findByPlaceholderText("タイトル");
    await user.type(input, "宿題");
    const button = await screen.findByText("追加");
    await user.click(button);

    const dbError = await screen.queryByText("Failed to add todo");
    expect(dbError).toBeNull();
  });

expect(dbError).not.toBeDefined() → expect(dbError).toBeNull()に変更しました。

原因は、
expect(null).toBeDefined()でもパスしてしまうことでした。

公式ドキュメントにもこういう記述があり、undefinedじゃない限りパスするようです。

toBeDefined asserts that the value is not equal to undefined. Useful use case would be to check if function returned anything.

参考文献

おわりに

細かい挙動はドキュメントを見るべきだと改めて感じました。

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