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

如何用Sinon正确Mock ElasticSearch Client的indices.stats方法

用Sinon正确Mock Elasticsearch indices.stats接口的方案

错误原因

你之前的写法报错,是因为Client.indices并不是构造函数,不存在prototype属性,直接去StubClient.indices.prototype.stats自然会抛出Cannot read property 'prototype' of undefined错误。

两种可行的Mock方案

方案一:直接Mock实例的indices.stats方法

你的业务代码里是用esClient这个实例调用indices.stats,所以直接针对该实例的方法Stub最直接:

const sinon = require('sinon');
const { Client } = require('@elastic/elasticsearch');

// 先创建ES客户端实例
const esClient = new Client({ node: 'some https url' });

// 模拟错误场景:触发回调时传入错误对象
sinon.stub(esClient.indices, 'stats').callsArgWith(1, new Error('Mocked ES request failed'));

// 模拟成功场景:触发回调时传入null(无错误)和模拟的返回数据
// sinon.stub(esClient.indices, 'stats').callsArgWith(1, null, {
//   indices: {
//     // 填入你需要模拟的统计数据结构
//     test_index: { total: { docs: { count: 100 } } }
//   }
// });

方案二:Mock Client类的原型(多实例场景适用)

如果你的代码会创建多个Client实例,或者需要在模块层面全局Mock,可以Stub Client原型的indices getter属性,返回带有Mock方法的对象:

const sinon = require('sinon');
const { Client } = require('@elastic/elasticsearch');

// Stub Client原型的indices getter,返回包含Mock stats方法的对象
sinon.stub(Client.prototype, 'indices').get(() => ({
  stats: sinon.stub().callsArgWith(1, new Error('Mocked ES error'))
}));

// 此时创建的所有Client实例,调用indices.stats都会使用Mock方法
const esClient = new Client({ node: 'some https url' });

关键注意点

  • 你的业务代码用的是回调风格调用,所以Stub时必须用callsArgWith触发回调参数(回调是indices.stats的第二个参数,所以索引填1);如果是Promise风格调用,才用returns(Promise.resolve(...))或rejects(...)。
  • 测试结束后记得调用stub.restore()恢复原方法,避免干扰其他测试用例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 20:10:25