I'm using mocha, chai, and chai-http to test my simple API that routes calls from Slack to Habitica, integrating these two services.
I'm trying to start by creating tests, but I'm facing this issue: when I call my API, the code returns before the external API call. This is the code of the test:
var chai = require("chai");
var chaiHttp = require("chai-http");
var server = require("../src/app/index");
var should = chai.should();
chai.use(chaiHttp);
describe("/GET list", () => {
it("it should return a list of user\'s tasks", (done) => {
chai.request(server)
.post("/habitica")
.type("urlencoded")
.send({text: "list"})
.end((err, res) => {
res.should.have.status(200);
res.body.should.be.a("object");
res.body.should.have.property("success").eql("true");
done();
});
});
});
This is the code that is been called by the test:
app.post("/habitica", server.urlencodedParser, function(req, res) {
if (typeof req.body !== "undefined" && req.body) {
switch(req.body.text) {
case "list":
request({
url: GET_TASKS,
headers: { "x-api-user": process.env.HABITICA_USERID, "x-api-key": process.env.HABITICA_APITOKEN }
}, function (apiError, apiResponse, apiBody) {
if (apiError) {
res.send(apiError);
} else {
res.send(apiBody);
}
});
break;
default:
res.send({
"success": "false",
"message": "Still working on tasks creation"
});
}
}
});
This code returns before the call to Habitica return any value. This is the result of "npm test":
/GET list
1) it should return a list of user's tasks
0 passing (2s)
1 failing
1) /GET list
it should return a list of user's tasks:
Uncaught AssertionError: expected {} to have property 'success'
at chai.request.post.type.send.end (test/app.js:17:34)
at Test.Request.callback (node_modules/superagent/lib/node/index.js:706:12)
at IncomingMessage.parser (node_modules/superagent/lib/node/index.js:906:18)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
I've already searched in a lot of forums and sites:
- Some people say that I shouldn't test code I don't own: this makes a lot of sense, but what should I've been testing since it is just a simple integration service?
- Some people say that I should mock the external api result: but I won't been testing anything since, again, it is just an integration.
How can I solve this?
Thanks in advance.