在没有 setTimeout 的情况下使用 elasticsearch 的后端测试失败
Back-end tests with elasticsearch fails without setTimeout
我正在为使用 MongoDB 和 Elasticsearch 的后端编写测试。问题是如果没有用 setTimeout
包装测试,测试就会失败,而且看起来 elasticsearch 无法在测试前将模拟数据索引到数据库中。这是代码:
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();
});
});
});
我正在为使用 MongoDB 和 Elasticsearch 的后端编写测试。问题是如果没有用 setTimeout
包装测试,测试就会失败,而且看起来 elasticsearch 无法在测试前将模拟数据索引到数据库中。这是代码:
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();
});
});
});