在 Jest 中模拟命名导出会抛出 TypeError: ...is not a function

问题描述 投票:0回答:1

我有一个 IconFactory.ts,它没有默认导出:

export class Icon {
  primary: string = "PR";
}

export interface IconFactory {
  createAsync(entity: Entity): Promise<Icon>;
}

export class MyIconFactory implements IconFactory {
  async createAsync(entity: Entity): Promise<Icon> {
    const icon = new Icon();
    //Some other logic
    return icon;
  }
}

在我的功能代码 Client.ts 中,我创建了 MyIconFactory 的实例:

import {
  MyIconFactory,
  type Icon,
} from "IconFactory";
export async function createIcon(entity: Entity){
  const iconFactory = new MyIconFactory();
  await iconFactory.createAsync(entity);
}

我正在尝试编写一个单元测试来测试 Client.createIcon(),通过在 Client.test.ts 中模拟 IconFactory.createAsync() :

import {
  Icon,
  MyIconFactory,
} from "IconFactory";
import { createIcon } from "Client";
const mockIcon = new Icon();
const mockCreate = jest.fn().mockResolvedValue(mockIcon);
jest.mock("IconFactory", () => {
  const originalModule = jest.requireActual(
    "IconFactory"
  );

  return {
    __esModule: true,
    ...originalModule,
    MyIconFactory: jest.fn().mockImplementation(() => {
      return { createAsync: mockCreate };
    }),
  };
});
it("should create markers when consignment addresses are overridden", async () => {
  Entity entity = new Entity();
  const result = createIcon(entity);
  //...Assertions
});

但是当它运行时,它会在

await iconFactory.createAsync(entity);
处抛出错误:TypeError: iconFactory.createAsync is not a function.

我在这里做错了什么吗?

提前致谢。

我也尝试过

jest.spyOn(IconFactory.prototype).mockResolvedValue(mockIcon);
但这根本没有嘲笑。 Client.createIcon() 仍然使用 iconFactory.createAsync 中的原始实现。

typescript jestjs mocking
1个回答
0
投票

可以使用

jest.spyOn()
,比
jest.mock()

简单
import { Icon } from './IconFactory';
import { createIcon } from './Client';
import { Entity } from './Entity';
import { MyIconFactory } from './IconFactory';

it('should create markers when consignment addresses are overridden', async () => {
  const mockIcon = new Icon();
  const createAsyncSpy = jest.spyOn(MyIconFactory.prototype, 'createAsync').mockResolvedValue(mockIcon);

  const entity = new Entity();
  await createIcon(entity);
  expect(createAsyncSpy).toHaveBeenCalledWith(entity);
  createAsyncSpy.mockRestore();
});
© www.soinside.com 2019 - 2024. All rights reserved.