首页 > 解决方案 > 仅在默认显式调用时才调用 Jest mock

问题描述

问题

使用jestTypescript,我试图模拟一些依赖项,并且使用不同的方法我得到了非常奇怪的行为。

"esModuleInterop": truetsconfig.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

解决方法

我找到了两种解决问题的方法:

但是,我对这两种解决方案都不满意。

问题

我登录packageJsontmp.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

标签: typescriptjestjs

解决方案


推荐阅读