I am testing my Input element by 2 way.
- adding value and click on button to "todo list" works fine
- adding value and enter the "input' field, but throws error.
I am seeking clarifications on the issue here. Here is my test code:
import { describe, vi, it, expect } from "vitest";
import { AddTodo } from "./AddItem";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
const updateTodo = vi.fn();
describe("Add Item component", () => {
it("should contain a input with button element", () => {
render(<AddTodo updateTodo={updateTodo} />);
expect(screen.getByRole("textbox")).toBeInTheDocument();
expect(screen.getByRole("button")).toBeInTheDocument();
});
it("should add a todo item into screen", async () => {
render(<AddTodo updateTodo={updateTodo} />);
const inputBox = await screen.findByRole("textbox");
const button = await screen.findByRole("button", { name: "+" });
await userEvent.type(inputBox, "First todo");
expect(inputBox).toHaveValue("First todo");
await userEvent.click(button);
expect(updateTodo).toHaveBeenCalledWith(
expect.objectContaining({ text: "First todo" })
);
});
it("should add a todo item into screen on enter", async () => { //fails
render(<AddTodo updateTodo={updateTodo} />);
const inputBox = await screen.findByTestId("todo-input");
await userEvent.type(inputBox, "Second todo");
await userEvent.keyboard("{enter}");
expect(updateTodo).toHaveBeenCalledWith(
expect.objectContaining({ text: "First todo" })
);
});
});
failing case
it("should not call the updateTodo when input not provided", async () => {
const user = userEvent.setup();
const { findByTestId } = render(<AddTodo updateTodo={updateTodo} />);
const inputBox = await findByTestId("todo-input");
user.type(inputBox, "");
await user.keyboard("{enter}");
expect(updateTodo).not.toHaveBeenCalled();
});
Error: AssertionError: expected "spy" to not be called at all, but actually been called 1 times