I am learning to use TypeScript with a ToDo app. I have added redux to it and now testing the application.
I am using cleaup()
provided by React-Testing-Library, which seems to be called, but my tests fail because the previous tests data is visible in the next test.
it('adds a todo when a user clicks on the "ADD" button', () => {
render(<App />);
const todo: string = "first task";
userEvent.type(screen.getByRole("textbox"), todo);
expect(screen.getByRole("textbox")).toHaveValue(todo);
userEvent.click(screen.getByRole("button"));
expect(screen.getByRole("textbox")).toBeEmptyDOMElement();
});
it("lists down all the todos", () => {
const { container } = render(<App />);
const todos: string[] = ["todo 1", "todo 2", "todo 3"];
todos.forEach((todo: string) => {
userEvent.type(screen.getByRole("textbox"), todo);
expect(screen.getByRole("textbox")).toHaveValue(todo);
userEvent.click(screen.getByRole("button"));
expect(screen.getByRole("textbox")).toBeEmptyDOMElement();
});
let querySelector = container.querySelector("#all-todos");
expect(querySelector).not.toBeNull();
// Use of ! => https://stackoverflow.com/a/63084260/379235
expect(querySelector!.childNodes.length).toBe(todos.length);
for (let i = 0; i < querySelector!.childNodes.length; i++) {
expect(querySelector!.childNodes.item(i).textContent).toBe(todos[i]);
}
});
How can I prove that? Just reverse the order of these tests and all tests pass.
I am not sure what is a better way to unmount the rendered tree, than calling the cleanup()
method.
I have a codesandbox link which reproduces this issue. You can find this at https://codesandbox.io/s/testing-library-cleanup-issue-57tdy
Can someone help me understand how to fix it?
Thank you