はじめに
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じゃない限りパスするようです。
toBeDefinedasserts that the value is not equal toundefined. Useful use case would be to check if function returned anything.
参考文献
おわりに
細かい挙動はドキュメントを見るべきだと改めて感じました。
