Search code examples
elasticsearchmocha.jssupertest

Back-end tests with elasticsearch fails without setTimeout


I am writing tests for back-end which uses MongoDB and Elasticsearch. The problem is that without wrapping test with setTimeout test fails, and it looks like elasticsearch can't index mock data into db before test. Here is the code:

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
});

I think you will agree that timeout is not an elegant and nice solution, which slows every test to 1 second or more. Maybe, am I missing something?


Solution

  • Found a solution, maybe it will be useful for someone. According to 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).

    So, in this case, done() should be called within another callback function:

    before((done) => {
      elasticClient.index(elasticMockData, function() {
         elasticClient.indices.refresh(function (err: any, res: any) {
            if (err) {
              return;
            }
            done();
         });
      });
    });