I am writing a Redux action to fulfill a unit test a but am having trouble with the mocked function call inside the test. I believe I have mocked completeRegistration
correctly, by importing the module it is declared in and then mocking the function from the module reference, but Jest says the function doesn't get called despite the console log statement confirming that the verified.data.success
condition is true
.
Any ideas what am I doing wrong? Thanks
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();
});
});
Output
verifyEmail action › calls completeRegistration function if successful
expect(jest.fn()).toBeCalled()
Expected number of calls: >= 1
Received number of calls: 0