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

问题描述 投票:6回答:3

我正在使用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的好模式。

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

javascript node.js unit-testing tdd sinon
3个回答
8
投票

一种可能的选择是使用proxyquire + 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 }
});

1
投票

如果您尝试使用不包装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(...)
         ....
    }
}

0
投票

我使用https://www.npmjs.com/package/nock成功,嘲笑在端口9200处对elasticsearch主机的调用。

© www.soinside.com 2019 - 2024. All rights reserved.