[英]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.