用 Jest 嘲笑的第三方库仍然尝试访问内部

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

我有这样的功能:

export type SendMessageParams = {
  chatSession?: ChatSession,
  // ... other params ...
};

const sendMessage = async ({
  chatSession,
  // ... other params ...
}: SendMessageParams): Promise<void> => {
  // await chatSession?.sendMessage()
  // somewhere in implementation
};

export default sendMessage;

ChatSession 来自

@google/generative-ai

我想在我的测试文件中模拟它:

let defaultParams: SendMessageParams;

beforeEach(() => {
  jest.mock('@google/generative-ai', () => ({
    ChatSession: {
      sendMessage: async (content: string) => content,
    },
  }));
  defaultParams = {
    chatSession: new ChatSession('', ''),
    // ... other params ...
  };
});

afterEach(() => {
  jest.clearAllMocks();
});

it('should send message', async () => {
  // await sendMessage();
});

当我运行

npm run test
时,我收到错误消息:

 FAIL  tests/logic/actions/sendMessage.test.ts
  ● should send message

    ReferenceError: fetch is not defined

      43 |   const sendMessageInner = async (messages: Message[]) => {
      44 |     setMessageListState(messages);
    > 45 |     const result = await chatSession?.sendMessage(content);
         |                    ^
      46 |     const responseText = result?.response.text();
      47 |     if (responseText) {
      48 |       const responseMessage: Message = {

      at makeRequest (node_modules/@google/generative-ai/dist/index.js:246:9)
      at generateContent (node_modules/@google/generative-ai/dist/index.js:655:28)
      at node_modules/@google/generative-ai/dist/index.js:890:25
      at ChatSession.sendMessage (node_modules/@google/generative-ai/dist/index.js:909:9)
      at sendMessageInner (src/logic/actions/sendMessage.ts:45:20)
      at src/logic/actions/sendMessage.ts:72:7
      at sendMessage (src/logic/actions/sendMessage.ts:59:3)
      at Object.<anonymous> (tests/logic/actions/sendMessage.test.ts:44:3)

...这暗示

chatSession.sendMessage
方法仍然使用真实的实现而不是模拟。

我想知道为什么会发生这种情况以及解决方案是什么。

提前致谢。


环境

  • 节点 20.11.0(lts/铁)
  • 开玩笑 29.7.0
  • @google/generative-ai
    0.5.0(如果相关)
javascript typescript unit-testing jestjs google-generativeai
1个回答
0
投票

因为

sendMessage
函数接受
chatSession
作为其参数。您可以创建一个模拟
chatSession
并将其传递给
sendMessage
。您不需要使用
jest.mock()

例如

index.ts

import { ChatSession } from "@google/generative-ai";

export type SendMessageParams = {
  chatSession?: ChatSession;
};

const sendMessage = async ({ chatSession }: SendMessageParams): Promise<void> => {
  await chatSession?.sendMessage('hello');
};

export default sendMessage;

index.test.ts

import { ChatSession } from '@google/generative-ai';
import sendMessage from '.';

it('should send message', async () => {
  const chatSession = {
    sendMessage: jest.fn().mockImplementation((content) => content),
  } as unknown as ChatSession;

  await sendMessage({ chatSession });
  expect(chatSession.sendMessage).toHaveBeenCalledWith('hello');
});
© www.soinside.com 2019 - 2024. All rights reserved.