尝试用 Jest 模拟 JavaScript 类的所有功能

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

我正在尝试模拟一个 JavaScript 服务类 (

AppInsightsService
),并将其传递给工具类 (
OrderHistoryTool
) 来使用。我不想从模拟返回任何数据 - 我只想忽略对服务函数的所有调用,并且还允许我在创建使用该服务的工具时传入模拟。

我尝试过在网上搜索时看到的各种例子,但它们对我不起作用。我确定我做错了什么,但我不确定它是什么。

这里是我想要模拟的服务类的概要:

@Injectable()
export class AppInsightsService {
  constructor(private readonly config: ConfigService) {
...
  }

  async postEvent(appInsightsEventDTO: AppInsightsEventDTO) {
...
  }
...

这里是使用该服务的工具类:

export class OrderHistoryTool extends DynamicStructuredTool {
  constructor(
    ...
    appInsightsService: AppInsightsService,
  ) {
    super({
...
      }),
      func: async (payload: OrderHistoryInput): Promise<string> => {
        appInsightsService.postEvent(
          {
            name: 'OrderHistoryRequested',
            properties: {
              conversationId: conversationId,
              athleteId: athleteId,
            },
          });
...

这是我的测试:

const appInsightsServiceMock = jest.mock('../../app-insights/app-insights.service', jest.fn());
import { AppInsightsService } from '../../app-insights/app-insights.service';

enableFetchMocks();

// NOTE: TRIED USING THIS TOO BUT SAME ERROR
// jest.mock('../../app-insights/app-insights.service', () => {
//   return {
//     AppInsightsService: jest.fn().mockImplementation(() => {
//       return jest.fn().mockImplementation(() => {
//         return undefined;
//       });
//     }),
//   };
// });

describe('orderHistory - unit tests', () => {

  it('verify correct output', async () => {

    // NOTE: TRIED USING THIS TOO BUT SAME ERROR
    // const appInsightsServiceMock = jest.fn();

    const orderHistoryTool = new OrderHistoryTool(
      ...
      appInsightsServiceMock as unknown as AppInsightsService,
    );

    const result = await orderHistoryTool.invoke(
      {
        orderNumber: '123456',
      },
    );

当我尝试运行测试时出现错误。当它尝试从服务执行

postEvent()
函数时失败:

    [tool/error] [1:tool:order_history] [37ms] Tool run errored with error: "appInsightsService.postEvent is not a function
    TypeError: appInsightsService.postEvent is not a function\n    at OrderHistoryTool.func (orderHistory.ts:63:28)\n    at OrderHistoryTool._call 

如何创建类的模拟来模拟所有函数,并允许用户像调用真实函数一样调用这些函数?

javascript jestjs mocking ts-jest
1个回答
0
投票

您应该模拟

appInsightsService
以满足
AppInsightsService
接口。由于在调用
appInsightsService.postEvent()
方法时会调用
orderHistoryTool.invoke()
方法,因此您应该为
appInsightsService
模拟对象定义此方法。

import { AppInsightsService } from './app-insights.service';
import { OrderHistoryTool } from './order-history-tool.service';

describe('orderHistory - unit tests', () => {
  it('verify correct output', async () => {
    const appInsightsServiceMock = {
      postEvent: jest.fn(),
    };
    const orderHistoryTool = new OrderHistoryTool(appInsightsServiceMock as unknown as AppInsightsService);
    await orderHistoryTool.invoke({ orderNumber: '123456' });
    expect(appInsightsServiceMock.postEvent).toHaveBeenCalledTimes(1);
  });
});

测试结果:

 PASS  stackoverflow/78845864/order-history-tool.service.test.ts (6.518 s)
  orderHistory - unit tests
    √ verify correct output (1 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        16.388 s
Ran all test suites related to changed files.
© www.soinside.com 2019 - 2024. All rights reserved.