When trying to mock the post call with Jest, I am getting error as:
TypeError: Cannot read properties of undefined (reading '1')
What is the cause of this? 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: "xyz@abc.com" });
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, "xyz@abc.com");
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: "xyz@abc.com" });
});
it is working fine after i remove jest.mock('axios');
here is the passing test:
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");
const rePass = screen.getByPlaceholderText("userPassword Repeat");
userEvent.type(password, "one");
userEvent.type(userName, "arif");
userEvent.type(email, "xyz@abc.com");
userEvent.type(rePass, "one");
const button = screen.queryByRole("button", { name: "Sign Up" }) as HTMLElement;
const payload = { userPassword: "one", userName: "arif", userEmail: "xyz@abc.com", userPasswordRep: "one" };
const mockFn = jest.fn();
axios.post = mockFn;
userEvent.click(button);
const apiCall = mockFn.mock.calls[0];
const body = apiCall[1];
expect(body).toEqual(payload);
});