Search code examples
reactjstypescriptreact-testing-libraryvitest

Vitest with React throws error as "expected "spy" to be called once, but got 0 times"


From my test I am getting 2 errors. When I do the click function test, getting an error as "expected "spy" to be called once, but got 0 times", while I pass the nested function getting an TypeScript error

Type '{ submitHandler: Mock<any, any>; }' is not assignable to type 'IntrinsicAttributes'.
  Property 'submitHandler' does not exist on type 'IntrinsicAttributes'.typescript(2322)

Not able to understand those issue.

Here is my test code: Login.spec.tsx

import { render, screen, cleanup, waitFor } from "@testing-library/react";
import { describe, it, expect, afterEach, beforeAll, vi } from "vitest";
import user from "@testing-library/user-event";
import { Login } from "./Login";
import { MemoryRouter, Routes, Route } from "react-router-dom";
describe("Login page", () => {
  const submitHandler = vi.fn();
  beforeAll(() => {
    render(
      <MemoryRouter>
        <Login submitHandler={submitHandler} />
      </MemoryRouter>,
    );
  });
  afterEach(cleanup);

  it("insures, presence of email,password and button", async () => {
    const emailInput = screen.getByLabelText(/Email Address/i);
    const passwordInput = screen.getByLabelText(/Password/i);
    const button = screen.getByRole("button", { name: /Sign In/i });
    expect(emailInput).toBeInTheDocument();
    expect(passwordInput).toBeInTheDocument();
    await user.click(button);
    expect(submitHandler).toHaveBeenCalledOnce();
  });
});

Live Demo for reference


Solution

  • I moved the assertion in to "waitFor" helper. it works.

    from here to :

    expect(submitHandler).toHaveBeenCalledOnce();
    

    Here:

     await waitFor(() => {
          expect(funHandler).toHaveBeenCalledTimes(1);
     });