我正在为使用MongoDB和Elasticsearch的后端编写测试。问题在于,如果不使用setTimeout
进行包装测试,测试将失败,并且似乎Elasticsearch在测试之前无法将模拟数据索引到db中。这是代码:
let elasticSearch = require('elasticsearch');
let elasticClient = new elasticSearch.Client({
host: 'localhost:9200'
});
let app = require('./dist/app'); //path to my application
let supertest = require('supertest');
before((done) => {
elasticClient.index(elasticMockData, function() {
done();
});
});
beforeEach(() => {
request = supertest(app);
});
it('should get data from elastic', () => {
setTimeout(() => { // if I comment this timeout, test will fail
request.get('/api/elastic')
.end((err, res) => {
expect(res.body.hits.hits.length).not.to.equal(0);
})
}, 1000); // if I comment this timeout, test will fail
});
我想您会同意,超时不是一种优雅且不错的解决方案,它将每项测试的速度减慢到1秒或更长。也许我想念什么吗?
最佳答案
找到了解决方案,也许对某人有用。
根据Elasticsearch docs:
By default, the document will be available for get() actions immediately, but will only be available for searching after an index refresh (which can happen automatically or manually).
因此,在这种情况下,应在另一个回调函数中调用
done()
:before((done) => {
elasticClient.index(elasticMockData, function() {
elasticClient.indices.refresh(function (err: any, res: any) {
if (err) {
return;
}
done();
});
});
});
关于elasticsearch - 没有setTimeout的Elasticsearch后端测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44175580/