2017-05-25 63 views
0

我正在爲使用MongoDB和Elasticsearch的後端編寫測試。問題是沒有用setTimeout進行包裝測試失敗,並且它看起來像elasticsearch不能在測試之前將模擬數據索引到db中。下面是代碼:使用elasticsearch進行後端測試失敗,無setTimeout

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秒以上。也許,我錯過了什麼?

回答

1

找到一個解決方案,也許它會對某人有用。 據Elasticsearch docs

默認情況下,該文件將可用於GET()立即行動,但將只可用於索引刷新(可自動或手動發生)後搜索。

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

因此,在這種情況下,done()應該被另一個回調函數中調用

相關問題