我正在使用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
组合
诗乃会伪造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主机的调用。