I have a test that creates a new "municipality" record with a POST call to an API... then in the same test, I want to GET it back and see if it was created successfully. The problem is, I think it's getting it back too fast (before the record was successfully created). How do I fix that? I don't want the "GET" to be called until the POST is complete.
My test looks like this:
it('Insert random muncipality with name of APIAutomation-CurrentDateTime', function (done) {
let newMuncID = 0;
//create a random string first for the name.
var currentDateTime = new Date().toLocaleString();
api.post('/rs/municipalities')
.set('Content-Type', 'application/json')
.send({
"muncplName": "APIAutomation-" + currentDateTime,
"effDate": "2018-01-25",
"provId": 8
})
.end(function (err, res) {
expect(res).to.have.property('status', 200);
expect(res.body).to.have.property('provId', 8);
newMuncID = res.body.muncplId;
done();
});
//Now, query it back out again
api.get('/rs/municipalities/' + newMuncID)
.set('Content-Type', 'application/json')
.end(function (err, res) {
expect(res.body).to.have.property("provId", 8);
done();
});
});
Initialising this code looks like this:
import {expect} from 'chai';
import 'mocha';
import {environment} from "../envConfig"
var supertest = require("supertest");
var tags = require('mocha-tags');
var api = supertest(environment.URL);
I found a good solution using the Async package. It allows you to make API calls in series. You can have it wait for the answer to come back before executing the next test.
The code ends up looking like this:
it('Change a municipality name', function (done) {
async.series([
function(cb) { //First API call is to get the municipality
api.get('/rs/municipalities/' + muncToBeAltered)
.set('Content-Type', 'application/json')
.end(function (err, res) {
actualVersion = res.body.version;
cb();
});
}, //end first - GET API call
function(cb) { //second API call is to make a change
api.put('/rs/municipalities/' + muncToBeAltered)
.set('Content-Type', 'application/json')
.send({
"muncplName": newMuncName,
"provId": "3",
"status": "01",
"version": actualVersion
})
.end(function (err, res) {
expect(res).to.have.property('status', 200);
cb();
});
}, //end second - PUT API call
], done);
});