mocking - 开玩笑模拟exports.name 无法正常工作
问题描述
我有以下js代码
exports.setupUserAccounts = config => {
//Implementation
};
它位于“共享/用户”文件夹中。现在在测试文件中,我正在尝试使用 jest 模拟此方法(我没有使用 DI)
我正在为此编写以下代码
jest.mock('shared/user')
现在,当我运行代码时,出现以下错误
setupUserAccounts不是一种方法
我也尝试以下
jest.mock('shared/user', () => ({
setupUserAccounts: jest.fn()
}));
现在,当我运行测试时,该函数根本没有被模拟。补充一点,我的源代码是 TypeScript 代码,我正在运行ts-jest
.
解决方案
这是一个单元测试工作示例:
index.ts
:
const { setupUserAccounts } = require('./shared/user');
export function main() {
return setupUserAccounts();
}
shared/user/index.ts
:
exports.setupUserAccounts = config => {
console.log('setupUserAccounts');
};
index.spec.ts
const { main } = require('./');
const { setupUserAccounts } = require('./shared/user');
jest.mock('./shared/user', () => {
return {
setupUserAccounts: jest.fn()
};
});
test('should mock setupUserAccounts correctly', () => {
expect(jest.isMockFunction(setupUserAccounts)).toBeTruthy();
(setupUserAccounts as jest.MockedFunction<typeof setupUserAccounts>).mockReturnValueOnce('fake data');
const actualValue = main();
expect(actualValue).toBe('fake data');
});
覆盖率 100% 的单元测试结果:
PASS src/stackoverflow/56961691/index.spec.ts
✓ should mock setupUserAccounts correctly (4ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 3.885s, estimated 8s
源代码:https ://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/56961691
推荐阅读
- oracle - 在不知道表名的情况下将变量声明为行类型时需要帮助
- python - 网页抓取图像(美丽的汤)到具有一个功能的目录中,试图将这些图像附加到另一个功能的列表中,挣扎
- elasticsearch - 混合睡眠模式下的弹性搜索 - 嵌入到应用程序中
- c# - ExecuteNonQuery 中的错误
- ruby-on-rails - Pundit 工作正常,但为未经授权的用户返回 200 而不是 401
- java - 有什么方法可以在 gradle 的子项目中使用根项目类
- android - 未调用 AlarmReceiver
- c++ - c++ CreateFile() 尝试在 win 10 中打开设备时返回 1(无效函数)
- javascript - 我应该使用 ajax 调用还是将状态地图及其相应城市分配给 javascript 变量
- java - 在 Java 中使用 ssh2 连接到受 RSA SecurID 保护的 linux 系统