elasticsearch - 没有setTimeout的Elasticsearch后端测试失败

标签 elasticsearch mocha supertest

我正在为使用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/

相关文章:

c# - 如何使用 Serilog 和 ElasticSearch 拥有不同的日志类型

elasticsearch - 为符合特定条件的文档添加排序优先级

node.js - 在mocha单元测试中,如何模拟全局变量?

javascript - 浏览器中的Istanbul.js

javascript - koa.js 注册后返回 404 "Not Found",而不是来自 ctx.body 的 token

javascript - 使用 Elasticsearch 的 Ajax 查询格式

elasticsearch - 在grafana中使用Elasticsearch范围查询

node.js - 在每个文本(Mocha,Elastic)之前清理索引

node.js - super 测试:检查 res.send() 之后发生的事情

javascript - 使用 Supertest 测试 Express 应用程序时,对第三方库的构造函数进行 stub