typescript - 仅在默认显式调用时才调用 Jest mock
问题描述
问题
使用jest
Typescript,我试图模拟一些依赖项,并且使用不同的方法我得到了非常奇怪的行为。
当"esModuleInterop": true
在tsconfig.json
:
tmp.ts
import packageJson from 'package-json';
export async function testFn() {
return packageJson('test');
}
tmp.test.ts
import {testFn} from './tmp';
import packageJson from 'package-json';
describe('testFn', () => {
it('should be able to mock', async () => {
(packageJson as any).default = jest.fn().mockImplementation(async () => 'hello');
await testFn();
expect(packageJson.default).toHaveBeenCalled();
});
});
上述测试失败:
Expected number of calls: >= 1
Received number of calls: 0
解决方法
我找到了两种解决问题的方法:
- 替换
return packageJson('test');
为return packageJson.default('test');
intmp.ts
可以解决问题。 - 设置
"esModuleInterop": false
_tsconfig.json
但是,我对这两种解决方案都不满意。
问题
我登录packageJson
:tmp.ts
[AsyncFunction: packageJson] {
default: [Circular],
PackageNotFoundError: [Function: PackageNotFoundError],
VersionNotFoundError: [Function: VersionNotFoundError]
}
调用两者packageJson(...)
并packageJson.default(...)
在未模拟时产生相同的结果(它返回给定 Npm 包的信息)。
我尝试了一个导入变体,tmp.test.ts
但得到了同样的错误:
import * as packageJson from 'package-json';
我还尝试了另一种模拟语法:
jest.mock('package-json', () => ({
default: jest.fn().mockImplementation(async () => 'hello'),
}));
但随后得到Matcher error: received value must be a mock or spy function
。
解决方案
推荐阅读
- reactjs - 如何在网格列中设置文本区域元素的样式?
- azure - Rust 中的 Azure Active Directory 身份验证
- docker - 如果运行一段时间,如何重新启动 docker 容器
- url - Apache RewriteRule 不带斜杠(/)
- django - 避免在Django中通过多对多表重复
- python - 如何在 Python SQL 查询中使用变量?
- primereact - PrimeFlex 网格渲染问题
- javascript - 将数字的数字相加并返回总和
- multithreading - 将 Task.Run 中的代码编组到调用线程
- php - 如何在laravel中修复没有未定义偏移量的检查权限?