I am trying to write a test for the following function.
function services(api){
request(`${api}?action=services`, function(err, res, body) {
if (!err && res.statusCode === 200){
var resJson = JSON.parse(body);
var numberOfServices = resJson.length;
console.log("Service called: services");
console.log("-----------");
for (i = 0; i < numberOfServices; i++){
console.log("Service ID: " + resJson[i].service);
console.log("Service Name: " + resJson[i].name);
console.log("-----------");
}
return resJson;
}
});
}
The test is checking to see if the function returns an object. resJson
is the object being returned and tested.
Below is the test case written using Mocha.js and Chai.js assertion library.
var chai = require('chai');
var assert = chai.assert;
var sendRequest = require('../request');
describe('Test 1', function() {
var api = 'http://instant-fans.com/api/v2';
it('services() should return an object of services', function(done) {
var object = sendRequest.services(api);
assert.isObject(object);
});
});
However, when I run the test it fails with the following console output. Saying that resJson
is undefined. I'm guessing that Mocha is trying to assert that resJson
is an object BEFORE the function services()
returns the object, but I am not sure how to resolve this.
Test 1
1) services() should return an object of services
0 passing (27ms)
1 failing
1) Test 1 services() should return an object of services:
AssertionError: expected undefined to be an object
at Function.assert.isObject (node_modules/chai/lib/chai/interface/assert.js:555:35)
at Context.<anonymous> (test/requestTest.js:11:16)
I have tried to search this online, I have seen people resolve this using done()
method. However in my case that does not work due to the fact I am using a callback inside my services()
function.