I built an API for a couchbase database, and I am currently working on writing tests with mocha for my HTTP requests. The issues which I am running into, is that my GET request test cannot find the data which was added with the POST request test. If the database has data stored in it before the tests are run, the GET request test will pass. But the data which it returns does not include the newly added data from the POST request test. I need to be able to run the tests on a clean database and have all the tests pass. I believe that the issue is being caused due to mocha's asynchronous nature, but I'm not really sure how to fix this. Here's my test cases.
Dependencies
const expect = require('chai').expect;
const request = require('supertest');
const app = require('../src/app');
POST request test
describe(`POST requests`, ()=>{
it('Add new data', function() {
return request(app)
.post('/someendpoint')
.set('Accept', 'application/json')
.set('Authorization', auth_token)
.send(newData)
.expect(200)
.then( function(res) {
expect(res.body).be.a('Object');
expect(res.body.id).be.a('string');
id = res.body.id;
})
});
});
GET request test
describe('GET requests', function() {
it('Get data', function() {
return request(app)
.get('/someendpoint')
.set('Accept', 'application/json')
.set('Authorization', auth_token)
.expect(200)
.then((res) => {
expect(res.body).be.a('Array');
})
});
});
Also, if it make a difference. Every time a POST request is made, a new document is created in the couchbase database
Here's a poor solution that I found (Edit)
before('timer for get data', function(){
for(let i = 0; i < 1000000000; i++){
}
})
it('get data', function() {
return request(app)
.get('/someendpoint')
.set('Accept', 'application/json')
.set('Authorization', auth_token)
.expect(200)
.then((res) => {
expect(res.body).be.a('Array');
});
});