免责声明:
我从内存中直接将其写入StackOverflow应答字段,因此它可能不是100%准确。
create-react-app
__mocks__
项目根目录中的文件夹。
__mocks__/axios.js
:
export default {
// since you are only testing "axios.post()", I'm only mocking "post"
post: jest.fn()
}
然后在父组件的测试中,可以为
post
返回200响应的函数(您正在测试的就是这种情况)。
__tests__/App.test.jsx
:
// in Jest context, this should load from __mocks__/axios.js
import axios from "axios";
test("When valid form is submitted, it should show a success message", () => {
// Axios itself returns a Promise, so the mock should as well
axios.post.mockImplementationOnce(
(url, formData) => Promise.resolve({
status: 200
})
);
const wrapper = mount(<App />);
// Optionally, test the default state to be an empty string
expect(wrapper.state()).toHaveProperty("message");
expect(wrapper.state().message).toBe("");
wrapper.find("input").at(0).simulate("change", {
target: {
value: "a@b.c",
}
});
wrapper.find("form").simulate("submit");
// Optionally, test if Axios was called
expect(axios.post).toHaveBeenCalled();
// More optionally, test if it was called with the correct email address
expect(axios.post).toHaveBeenCalledWith(
expect.any(),
expect.objectContaining({ primaryEmail: "a@b.c" })
);
// Note that even though Axios may have been called, the asynchronous
// Promise may not have completed yet which means the state will not
// have been updated yet. To be safe, let's use setImmediate(), which
// should wait for any pending Promises to complete first
setImmediate(async () => {
// Now we can test that the state has changed
expect(wrapper.state().message).toBe("Your email has been updated.");
});
});