[英]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.