Here is the component code :
function SignUpPage() {
return (
<>
<h1>Sign Up</h1>
<input name="userName" />
</>
);
}
export default SignUpPage;
testing the same:
it("has input", () => {
render(<SignUpPage />);
const input = screen.queryByRole("input", { name: /userName/i });
expect(input).toBeInTheDocument();
});
but throws an error as:
received value must be an HTMLElement or an SVGElement.
Received has value: null
how to get by role by input element? thanks in advance.
CodePudding user response:
Input elements don't have "input" role by default. And input is an abstract role, you shouldn't use it, according by MDN
The input role is an abstract role. It must not be used by web authors.
You can use "textbox" role instead, for example.
And your using of queryByRole is correct, according to the documentations
If you only query for a single element with getByText('The name') it's oftentimes better to use getByRole(expectedRole, { name: 'The name' }).
Update In your case it's better to use other queries like getByLabelText, getByTestId or getByPlaceholderText
1.
<input name="userName" aria-label="Username" />
it("has input", () => {
render(<SignUpPage />);
const input = screen.queryByLabelText("Username");
expect(input).toBeInTheDocument();
});
<input name="userName" placeholder="Username" />
it("has input", () => {
render(<SignUpPage />);
const input = screen. getByPlaceholderText("Username");
expect(input).toBeInTheDocument();
});
<input name="userName" data-testid="usernameInput" />
it("has input", () => {
render(<SignUpPage />);
const input = screen. getByTestId("usernameInput");
expect(input).toBeInTheDocument();
});