I am not sure how I can set values to the useState variables which are outside of the test file. I don’t have any props to the components as I am getting the data directly inside components using Axios.
export const AddTodo = () => {
const [title, setTitle] = useState("");
const [desc, setdesc] = useState("");
const [error, seterror] = useState(false);
const [descError, setdescError] = useState("");
const [dbError, setdbError] = useState(false);
const submit = (e) => {
e.preventDefault();
title.length < 3 && seterror(true);
desc.length < 5 && setdescError(true);
console.log("Title and description", title, desc);
if (!(title.length < 3 || desc.length < 5)) {
setsrno(toDos[toDos.length - 1].srno + 1);
const task = { title, desc };
console.log("here is task", task);
setTitle("");
setdesc("");
fetch("http://localhost:3031/todo", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(task),
})
.then(() => {
console.log("new task added");
})
.catch((err) => {
return console.log(err), setdbError(true);
});
}
};
return(<div className="container my-3">
<form onSubmit={submit}>
<div className="mb-3" data-testid="todo-title">
<label htmlFor="title" className="form-label">
Todo Title
</label>
<input
type="text"
value={title}
onChange={(e) => {
setTitle(e.target.value);
titleValidation();
}}
className="form-control"
id="titleId"
aria-describedby="titleH"
/>
</div>
<div className="mb-3" data-testid="todo-desc">
<label htmlFor="desc" className="form-label">
Description
</label>
<input
type="text"
value={desc}
onChange={(e) => {
setdesc(e.target.value);
descValidation();
}}
className="form-control"
id="desc"
/>
{dbError ? <DbErrorModal dbModal={true} /> : <div></div>}
<button type="submit" className="btn btn-sm btn-success">
Add Todo
</button>
</form>
);
};
How can I call setTitle() and setdesc() method?
test("Should fire button", () => {
const { getByRole } = render(<AddTodo />, { wrapper: BrowserRouter });
const addTodoBtn = getByRole("button", { name: "Add Todo" });
fireEvent.click(addTodoBtn);
});