[英]Mock a const defined in a function using Jest
我的項目是一個使用 Jest 的 React 應用程序。
我必須測試一個我在其中定義 const 的函數。 const 是使用導入的服務設置的。
我想模擬 const 以測試 if-else 語句
這是我要測試的文件:
import { authenticationService } from "../_services/authentication.service";
export const handleHeaders = (isFile = false) => {
const currentUser = authenticationService.currentUserValue;
if (currentUser && currentUser.access_token) {
return isFile
? {
Authorization: `Bearer ${currentUser.access_token}`,
"Content-Disposition": "multipart/form-data"
}
: {
Authorization: `Bearer ${currentUser.access_token}`,
"Content-Type": "application/json"
};
} else {
return { "Content-Type": "application/json" };
}
};
我試圖模擬如下所示的身份驗證服務
import { handleHeaders } from "../handle-headers";
jest.mock("../../_services/authentication.service", () => ({
currentUserValue: { access_token: "some token" }
}));
describe("handleHeaders", () => {
it("should return headers with Authorization if
currentUser.access_token is defined", () => {
expect(handleHeaders()).toStrictEqual({
Authorization: "Bearer some token",
"Content-Type": "application/json"
});
});
});
但是我得到 TypeError: Cannot read property 'currentUserValue' of undefined 當函數試圖定義 const currentUser 時。
謝謝你的幫助
您可以使用 ES6 模擬: https ://jestjs.io/docs/en/es6-class-mocks
句法:
jest.mock('../_services/authentication.service', () => ({
__esModule: true,
authenticationService: {
currentUserValue: { access_token: 'some token' }
}
}))
但是,請記住在您的beforeEach
塊中調用authenticationService.mockClear()
以在測試之間重置它。
編輯:因為 authenticationService 不是默認導出,我們需要以這種方式模擬它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.