I am trying to test a simple user click button where the counter will increase from 0 to 1. Here is my counter button
import { useState } from "react";
export const Counter = () => {
const [counter, setCounter] = useState(0);
return (
<>
<h1>{counter}</h1>
<button onClick={() => setCounter(count => count + 1)} >INCREMENT +</button>
</>)};
and corresponding test for it
import {render, screen} from "@testing-library/react"
import { Counter } from "./Counter";
import { user } from "@testing-library/user-event";
import "./Counter";
test("renders count of 1 when clicking on INCREMENT + button", async () => {
user.setup()
render(<Counter />)
const incrBtn = screen.getByRole("button", {
name: "INCREMENT +"
});
await user.click(incrBtn);
const countElmnt = screen.getByRole("heading");
expect(countElmnt).toHaveTextContent("1");
});
I am using the following dependencies
"dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"devDependencies": {
"@testing-library/dom": "^9.3.1",
"@testing-library/user-event": "^14.4.3"
}
I get the following error
error received in vs code terminal
can someone tell me what i am doing wrong here?
I tried this command
npm install --save-dev @testing-library/user-event @testing-library/dom
to install latest version of user-event testing-library.
I am expecting a successful completion of click event test when I click on INCREMENT + button, the test should be successfully passed.
2
Answers
I have solved the issue, it was related to package updating.
I simply uninstall and again install the 'user-event' library from terminal, hitting this command. npm uninstall @testing-library/user-event npm install @testing-library/user-event
and I got the updated package in package.json file "@testing-library/user-event": "^14.4.3", "@testing-library/react": "^13.4.0",
and I added this code and it worked! Thank you Lin for the inputs about user and userEvent imports.
it seems like you’re using an outdated version of
@testing-library/react
. The latest version as of my knowledge cutoff date (September 2021) is12.1.2
, but in your package.json, you have"@testing-library/react": "^13.4.0"
.To resolve the issue, you can try updating your
@testing-library/react
and related dependencies to the latest version by running the following command:Additionally, there’s no need to import
"./Counter"
in your test file since you are already importing theCounter
component directly.After updating the dependencies, your code should look like this:
Make sure to restart your test runner after updating the dependencies to ensure they are loaded correctly.
With these changes, the test should work as expected, and the counter should increase from 0 to 1 when clicking on the "INCREMENT +" button.