Search code examples
node.jsunit-testingelasticsearchmocha.jssinon

How to mock stats method in elasticsearch?


I want to query stats of elasticsearch using nodeJs.

Here is my source code

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

How do i mock this elasticsearch method?
I have tried following but it is unable to mock the stats().

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

Where am I going wrong here?


Solution

  • Let's see how the nodes API is defined. See /v8.8.1/src/api/index.ts#L401, you will find the nodes API is defined by Object.defineProperties with a getter function.

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

    We should use stub.get(getterFn) API to replace a new getter for this stub.

    E.g.

    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);
        });
    });