如何在elasticsearch中模拟stats方法?

iszxjhcz  于 2023-08-03  发布在  ElasticSearch
关注(0)|答案(1)|浏览(71)

我想使用nodeJs查询elasticsearch的stats。
下面是我的源代码

const {Client}  = require('@elastic/elasticsearch');
client = new Client({
Connection:'appropriate aws connection',
node:'some url',
agent:{
  keepalive:,
  maxsocket:,
  maxfreesocket:
}
})

const stats = await client.nodes.stats();

console.log(stats);

// some operation on stats

字符串
我如何模仿这个elasticsearch方法?
我试过以下,但它无法模拟stats()

let sandbox = sinon.createSandbox();
 before(()=>{
   sandbox.stub(Client.prototype,'nodes').get(()=>{
      stats: ()=>{
       return dymmydata;
     }
//where dummydata is already hardcoded
   })
 })


我哪里做错了?

ffdz8vbo

ffdz8vbo1#

让我们看看nodes API是如何定义的。参见/v8.8.1/src/api/index.ts#L401,您会发现nodes API是由Object.defineProperties通过getter函数定义的。

Object.defineProperties(API.prototype, {
  // ...
  nodes: {
    get () { return this[kNodes] === null ? (this[kNodes] = new NodesApi(this.transport)) : this[kNodes] }
  }
  // ...
}

字符串
我们应该使用stub.get(getterFn) API来替换这个存根的新getter。
例如:
index.js

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

const client = new Client({
    node: 'http://localhost:9200',
});

export function main() {
    return client.nodes.stats();
}


index.test.js

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

describe('76653113', () => {
    it('should pass', async () => {
        const nodesApiMock = {
            stats: sinon.stub().resolves('ok'),
        };
        sinon.stub(Client.prototype, 'nodes').get(() => nodesApiMock);
        const { main } = require('./');
        const actual = await main();
        sinon.assert.match(actual, 'ok');
        sinon.assert.calledOnce(nodesApiMock.stats);
    });
});

相关问题