javascript - 使用 Jest 模拟函数中定义的 const
问题描述
我的项目是一个使用 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' }
}
}))
但是,请记住authenticationService.mockClear()
在您的beforeEach
块中调用以在测试之间重置它。
编辑:因为 authenticationService 不是默认导出,我们需要以这种方式模拟它。
推荐阅读
- python - 使用列表列表字典的字典初始化嵌套数据结构
- c++ - 将 Win32/WinAPI 应用程序移植到 wxWidgets
- c++ - 为什么我的节点设置为 nullptr 在我设置它 = 新节点之后?
- c - fprintf 在 txt 文件中写入 0D 0D 0A 而不是 0D 0A
- c - 如何在神经网络的权重上应用梯度下降?
- python - 使用 splitlines 和 Split 获取单词的行
- http - CSRF 保护同时利用服务器端缓存
- powershell - 有哪些不同的 PowerShell 文件类型?
- python-3.x - 在 Python 3.6 中运行 scrapyd
- javascript - web3-react 导致我的应用程序挂起而没有错误