Here is the test for the :
it("changes the state when body input is changed", () => {
render(<CommentForm />)
// let input = screen.getByLabelText("Your Name");
let input = screen.getByRole("textbox", { name: "Your Comment" });
fireEvent.change(input, { target: { value: "MyComment" } });
expect(input.value).toEqual("MyComment");
});
With the commented line it works (when I search with getByLabelText
). Here is what I am getting when I try to find it with getByRole
:
Unable to find an accessible element with the role "textbox" and name "Your Comment"
Here are the accessible roles:
document:
Name "":
<body />
--------------------------------------------------
generic:
Name "":
<div />
Name "":
<div
class="input-group"
/>
Name "":
<div
class="input-group"
/>
--------------------------------------------------
heading:
Name "Post a Comment":
<h2 />
--------------------------------------------------
textbox:
Name "Your Name":
<input
id="author-name"
name="author"
type="text"
value=""
/>
Name "":
<textarea
cols="30"
id="body"
name="body"
rows="10"
/>
So it seems like the name is empty but I am not sure why that is.
And here is the actual component:
import React from "react";
import useInput from "../hooks/useInput";
const CommentForm = ({ onSubmit }) => {
const { value: author, reset: resetAuthor, bind: bindAuthor } = useInput("");
const { value: body, reset: resetBody, bind: bindBody } = useInput("");
const handleSubmit = (e) => {
e.preventDefault();
onSubmit({ author, body }, resetInputs);
};
const resetInputs = () => {
resetAuthor();
resetBody();
};
return (
<form onSubmit={handleSubmit}>
<h2>Post a Comment</h2>
<div className="input-group">
<label htmlFor="author-name">Your Name</label>
<input id="author-name" type="text" name="author" {...bindAuthor} />
</div>
<div className="input-group">
<label htmlFor="body">Your Comment</label>
<textarea
id="body"
name="body"
cols="30"
rows="10"
{...bindBody}
></textarea>
</div>
<button type="submit">Submit</button>
</form>
);
};
export default CommentForm;
Can anyone see the issue here. I am sure it should work and I don't see any reason why the author input can be grabbed with getByRole
and name but this one can't.