【发布时间】:2020-04-30 11:34:54
【问题描述】:
我正在编写一个 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
【问题讨论】:
-
嗨@andy,在你的测试中,我看不到
verifyEmail是从哪里导入的。是否在放置completeRegistration方法的同一文件中?您能否更新您的问题以在您的测试中包含verifyEmail的导入? -
有一个错字,谢谢你捡起它。所以
import * as auth from "../../actions/auth";引入了verifyEmail,它被称为auth.verifyEmail -
那你的问题已经解决了吗?
-
不幸的是不是,这是我在发布问题时犯的一个错字。问题中的代码现在与我的编辑器中的代码相同
标签: javascript redux jestjs moxios