我的项目是一个使用 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" };
}
};
我尝试像下面这样模拟 auth 身份验证服务
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
block 中调用 authenticationService.mockClear()
以在测试之间重置此设置。
编辑:因为authenticationService不是默认导出,所以我们需要以这种方式模拟它。
关于javascript - 使用 Jest 模拟函数中定义的 const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59626847/