Why does `userEvent.click` not trigger a form submission with Vitest and React Testing Library?
Asked Answered
B

0

7

The following test runs and passes just fine when using Create React App out of the box.

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import App from "./App";

describe("Update the name", () => {
  it("updates the name", () => {
    render(<App />);
    userEvent.type(screen.getByLabelText(/name/i), "John");
    userEvent.click(screen.getByRole("button"));

    expect(screen.getByText("John")).toBeInTheDocument();
  });
});

So, the test itself should be just fine. Yes, there is only 1️⃣ button, and that is type="submit". App works when running in browser and tests are fine in Create React App (CRA).

I am trying to move to Vitest (with Vite). Theoretically, no changes should be necessary to the above test. However, here's what happens: TypeError: target.ownerDocument.createRange is not a function.

Let's get to the configurations.

vite.config.js looks πŸ‘€ like this:

/// <reference types="vitest" />
/// <reference types="vite/client" />

import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  test: {
    globals: true,
    environment: "happy-dom",
    setupFiles: "./src/setup.js",
  },
});

./src/setup.js looks like this: import "happy-dom";

Yes, I also tried with jsdom.

I also replaced userEvent.click with fireEvent.click. I also added a data-testid to my form and tried fireEvent.submit directly on that form.

In the latter scenarios, no errors but either the form submit wasn't triggered, or the submission was triggered, but the render was not updated.

Fact of the matter is if the πŸ’© works in CRA, then the test should not have to be changed. Possibly only the configurations. πŸ˜–

I love Vite, but can't continue with it if I can't get the testing βœ… experience working.

Bolen answered 22/6, 2022 at 0:58 Comment(5)
userEvents are async methods. try using await userEvent.type(screen.getByLabelText(/name/i), "John"); await userEvent.click(screen.getByRole("button"));. To make it work the it callback should be async as well – Hardiness
Yeah. Got that figured a while ago. Forgot to post back. Tx. – Bolen
Doesn't solve it for me. I'm migrating from Jest to Vitest and facing the same problem. I'm already await'ing and my test function is async. It works in Jest. – Glabrescent
Have a snippet to look at? Actually, since this time, I've been using Cypress more than React Testing Library and much less 'game playing' with awaits and such. Cypress is smart enough to behave like the user and automatically 'await.' – Bolen
Just faced with the same problem. Did you fix that? – Devoted

© 2022 - 2024 β€” McMap. All rights reserved.