我正在编写一个 Redux 操作来完成一个单元测试,但是在测试中的模拟函数调用有问题。我相信我已经completeRegistration
正确地模拟了,通过导入声明它的模块,然后从模块引用中模拟函数,但是 Jest 说尽管控制台日志语句确认verified.data.success
条件是true
.
任何想法我做错了什么?谢谢
auth.js
export const verifyEmail = ({
originalCode,
confirmCode,
token
}) => async dispatch => {
try {
const body = JSON.stringify({
originalCode,
confirmCode,
registering: true
});
const verified = await axios.post("/api/email/verify", body, config);
if (verified.data.success) {
console.log("Success!") // logs "Success!"
completeRegistration(token); // test is to find out if this function gets called
} else {
return { msg: "Code did not match, please try again" };
}
} catch (err) {
dispatch({
type: REGISTER_FAILED
});
}
};
auth.test.js
import * as auth from "../../actions/auth";
const originalCompleteReg = auth.completeRegistration;
describe("verifyEmail action", () => {
let verifyData;
beforeEach(() => {
verifyData = {
originalCode: "1234546",
confirmCode: "1234546",
token: "87618g1u8ojb98k3jb12i3kwdbcjwvbbi92ueg29eubv" // fake data :p
};
auth.completeRegistration = jest.fn(() => auth.completeRegistration);
moxios.install();
});
afterEach(() => {
auth.completeRegistration = originalCompleteReg;
moxios.uninstall();
});
it("calls completeRegistration function if successful", async () => {
moxios.wait(() => {
const request = moxios.requests.mostRecent();
request.respondWith({
status: 200,
response: { success: true }
});
});
const store = mockStore({ payload: {} });
await store.dispatch(auth.verifyEmail(verifyData));
expect(auth.completeRegistration).toBeCalled();
});
});
输出
verifyEmail action › calls completeRegistration function if successful
expect(jest.fn()).toBeCalled()
Expected number of calls: >= 1
Received number of calls: 0