[英]Testing if a function is called inside another function Jest
我正在編寫一個 Redux 操作來完成單元測試,但是在測試中模擬的 function 調用遇到問題。 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是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();
});
});
Output
verifyEmail action › calls completeRegistration function if successful
expect(jest.fn()).toBeCalled()
Expected number of calls: >= 1
Received number of calls: 0
問題是您不是 mocking auth
模塊中verifyEmail
使用的completeRegistration
的內部值,而是導出的值。
當你導入一個模塊時,你會得到一個 object 並引用模塊的功能。 如果您覆蓋所需模塊中的值,您自己的引用將被覆蓋,但實現保留原始引用。
因此,在您的情況下,如果您在測試文件中調用auth.completeRegistration
,您將調用模擬版本。 但是當調用auth.verifyEmail
(內部調用completeRegistration
)時,它引用的completeRegistration
不是您覆蓋的版本。
我認為你不應該測試你的completeRegistration
方法是否被調用(畢竟,這是一個實現細節)。 相反,您應該檢查您的方法的行為是否符合預期(即completeRegistration
的行為,無論是重定向到另一個頁面、執行附加請求、保存 cookie 等)。 因此,您將是 mocking API 正在用於completeRegistration
但不是方法本身。
話雖如此,如果您想檢查是否調用了completeRegistration
,您仍然有幾個選擇。
您必須安裝插件並將其添加到您的 babel 配置中。 完成此操作后,您的測試將如下所示:
import AuthModule from '../../actions/auth';
import * as auth from '../../actions/auth';
describe('verifyEmail action', () => {
let verifyData;
beforeEach(() => {
verifyData = {
originalCode: '1234546',
confirmCode: '1234546',
token: '87618g1u8ojb98k3jb12i3kwdbcjwvbbi92ueg29eubv'
};
moxios.install();
});
afterEach(() => {
moxios.uninstall();
});
it('calls completeRegistration function if successful', async () => {
moxios.wait(() => {
const request = moxios.requests.mostRecent();
request.respondWith({
status: 200,
response: { success: true }
});
});
const mockFn = jest.fn();
AuthModule.__Rewire__('completeRegistration', mockFn);
const store = mockStore({ payload: {} });
await store.dispatch(auth.verifyEmail(verifyData));
expect(mockFn).toHaveBeenCalled();
AuthModule.__ResetDependency__('completeRegistration');
});
});
您可以為completeRegistration
function 創建一個單獨的模塊。 這樣,由於您的auth.js必須導入模塊,您將能夠使用jest.mock
功能模擬模塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.