when try to mock the post call with jest getting error as:
TypeError: Cannot read properties of undefined (reading '1')
any one help me to understand please? here is the spect code:
const mockFn = jest.fn();
axios.post = mockFn;
userEvent.click(button);
const apiCall = mockFn.mock.calls[0];
const body = apiCall[1];
expect(body).toEqual({ userName: "arif", password: "one", email: "[email protected]" });
template:
const submit = (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
event.preventDefault();
axios.post("/api/1.0/users", formData);
setFormData(initialFormProps);
};
html:
<form action="" autoComplete="off">
<h1>Sign Up</h1>
<input type="text" placeholder="userName" onChange={handleChange} defaultValue={formData.userName} name="userName" />
<input type="email" placeholder="userEmail" onChange={handleChange} defaultValue={formData.userEmail} name="userEmail" />
<input type="password" defaultValue={formData.userPassword} onChange={handleChange} placeholder="userPassword" name="userPassword" />
<input type="password" defaultValue={formData.userPasswordRep} onChange={handleChange} placeholder="userPassword Repeat" name="userPasswordRep" />
<button disabled={isSubmit} onClick={submit}>
Sign Up{" "}
</button>
</form>
testing part:
it("sends username, email and password to backend after clicking submit", async () => {
render(<SignUpPage />);
const password = screen.getByPlaceholderText("userPassword");
const userName = screen.getByPlaceholderText("userName");
const email = screen.getByPlaceholderText("userEmail");
userEvent.type(password, "one");
userEvent.type(userName, "arif");
userEvent.type(email, "[email protected]");
const button = screen.queryByRole("button", { name: "Sign Up" }) as HTMLElement;
const mockFn = jest.fn();
axios.post = mockFn;
userEvent.click(button);
const apiCall = mockFn.mock.calls[0];
const body = apiCall[1];
expect(body).toEqual({ userName: "arif", password: "one", email: "[email protected]" });
});
it is working fine after i remove
jest.mock('axios');
here is the passing test: