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.
await userEvent.type(screen.getByLabelText(/name/i), "John"); await userEvent.click(screen.getByRole("button"));
. To make it work theit
callback should beasync
as well β Hardinessawait
s and such. Cypress is smart enough to behave like the user and automatically 'await.' β Bolen