You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Jest正确Mock OpenSearch的indices.exists方法?

问题

使用OpenSearch客户端测试indices.exists方法时,Jest测试报错:openSearchClient.indices.exists is not a function。需要Mock的是mockOpenSearchClient.indices.exists(),但当前Mock实际模拟的是mockOpenSearchClient.indices().exists(),调整配置后仍未解决。

初始Mock配置

const mockOpenSearchClient = {
  indices: jest.fn().mockImplementation(() => {
    return {
      exists: jest.fn((obj, cb) => {
        return cb("", existsResp);
      }),
    };
  }),
} as unknown as Client;

调整后的Mock配置

const mockOpenSearchClient = {
  indices: jest.fn().mockImplementation(() => {
    return {
      exists: jest.fn().mockImplementation(() => {
        return {
          statusCode: 200,
          body: true,
        };
      }),
    };
  }),
} as unknown as Client;

日志输出

openSearchClient {
      indices: [Function: mockConstructor] {
        _isMockFunction: true,
        getMockImplementation: [Function (anonymous)],
        mock: [Getter/Setter],
        mockClear: [Function (anonymous)],
        mockReset: [Function (anonymous)],
        mockRestore: [Function (anonymous)],
        mockReturnValueOnce: [Function (anonymous)],
        mockResolvedValueOnce: [Function (anonymous)],
        mockRejectedValueOnce: [Function (anonymous)],
        mockReturnValue: [Function (anonymous)],
        mockResolvedValue: [Function (anonymous)],
        mockRejectedValue: [Function (anonymous)],
        mockImplementationOnce: [Function (anonymous)],
        withImplementation: [Function: bound withImplementation],
        mockImplementation: [Function (anonymous)],
        mockReturnThis: [Function (anonymous)],
        mockName: [Function (anonymous)],
        getMockName: [Function (anonymous)]
      }
    }

解决方案

问题核心在于你错误地把indices模拟成了一个函数,但实际OpenSearch客户端中indices是一个对象,exists是该对象的直接属性方法,而非调用indices()后返回对象的方法。

日志里也能明确看出问题:indices是一个mock函数([Function: mockConstructor]),所以访问indices.exists自然会提示“不是函数”——函数本身没有exists属性,只有调用这个函数返回的对象才有。

正确的Mock写法

根据你业务代码实际使用的调用风格,选择对应的Mock:

1. 回调风格(对应你初始代码的回调逻辑)

const mockOpenSearchClient = {
  indices: {
    exists: jest.fn((obj, cb) => {
      cb("", existsResp); // 直接执行传入的回调函数
    }),
  },
} as unknown as Client;

2. Promise风格(如果业务代码用了async/await)

如果indices.exists返回Promise,用下面的方式Mock:

const mockOpenSearchClient = {
  indices: {
    exists: jest.fn().mockResolvedValue({
      statusCode: 200,
      body: true,
    }),
  },
} as unknown as Client;

验证方式

Mock完成后,可以在测试代码里添加一行打印,确认indices的结构:

console.log(mockOpenSearchClient.indices);
// 正确输出应为 { exists: [MockFunction] },而非函数类型

内容的提问来源于stack exchange,提问作者Tim Chosen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 04:05:53