简体   繁体   中英

How to mock an instance of elasticsearch in Node.js?

I am using elasticsearch and would like to write a unit test for the following code:

import * as elasticsearch from "elasticsearch";
import config from "../config";

const client = new elasticsearch.Client({
  host: config.elasticsearch.host,
  log: "trace"
});

export function index(data) {
    return new Promise((resolve, reject) => {
        client.create({
            index: "myindex",
            type: "mytype",
            id: booking.urn,
            body: data
        }).then(resolve, reject);
    });
}

I am familiar with mocha and sinon, however I don't know of a good pattern to use to stub\\mock client.create in this case.

Can anyone suggest an approach that I could use?

One possible option is to use proxyquire + sinon combo

Sinon will fake Client :

const FakeClient = sinon.stub();
FakeClient.prototype.create = sinon.stub().returns("your data");
var fakeClient = new FakeClient();
console.log(fakeClient.create()); // -> "your data"

Such fake client can be passed into module under test by injection via proxyquire :

import proxyquire from 'proxyquire';
const index = proxyquire('./your/index/module', {
  'elasticsearch': { Client: FakeClient }
});

The answer of luboskrnac will works if you are trying to proxiquire module that doesn't wrap elasticsearch client, otherwise you need to proxiquire nested elasticsearch client.

// controller.spec.js

const FakeClient = {};    
FakeClient.search = () => {};
sinon.stub(FakeClient, 'search').callsFake((params, cb) => cb(null, {
    hits: {
        hits: [{
            _source: {
                id: '95254ea9-a0bd-4c26-b5e2-3e9ef819571d',
            },
        }],
    },
}));

controller = proxyquire('./controller', {
    '../components/es.wrapper': FakeClient,
    '@global': true,
});

wrapper

// components/es.wrapper.js

const elasticsearch = require('elasticsearch');

const client = new elasticsearch.Client({
    host: process.env.ELASTICSEARCH_HOST,
});

const wrapper = (method, params, callback) => {
    if (process.env.NODE_ENV === 'development') {
        params.index = `dev_${params.index}`;
    }
    return client[method](params, callback);
};

// Wrap ES client methods with dev env prefix
module.exports = {
    search: (params, callback) => {
        return wrapper('search', params, callback);
    },
}

controller

// controller.js
const es = require('../components/es.wrapper');

module.exports = {
    search: (req, res, next) => {
         ....
         es.search(...)
         ....
    }
}

我成功使用https://www.npmjs.com/package/nock ,模拟了端口9200对elasticsearch主机的调用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM