繁体   English   中英

如何在Node.js中模拟elasticsearch的实例?

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

我正在使用elasticsearch,并希望为以下代码编写单元测试:

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

我熟悉mocha和sinon,但是我不知道在这种情况下使用stub \\ mock client.create的好模式。

任何人都可以建议我可以使用的方法吗?

一种可能的选择是使用proxyquire + sinon组合

Sinon将伪造Client

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

这样的假客户端可以通过proxyquire注入传入被测模块:

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

如果您尝试使用不包装elasticsearch客户端的模块,则luboskrnac的答案将有效,否则您需要proxiquire嵌套的elasticsearch客户端。

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

包装纸

// 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.js
const es = require('../components/es.wrapper');

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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