I'm trying to get the grasp of the tool Nock in order to mock the request and response from my code doing the calls. I'm using npm request as a simple HTTP client to request the back-end REST API, Chai for the expectation library and Mocha to run my tests. Here is the code that I have for the tests:
var nock = require('nock');
var storyController = require('../modules/storyController');
var getIssueResponse = {
//JSON object that we expect from the API response.
}
it('It should get the issue JSON response', function(done) {
nock('https://username.atlassian.net')
.get('/rest/api/latest/issue/AL-6')
.reply(200, getIssueResponse);
storyController.getStoryStatus("AL-6", function(error, issueResponse) {
var jsonResponse = JSON.parse(issueResponse);
expect(jsonResponse).to.be.a('object');
done();
})
});
And here is the code to do the GET request:
function getStoryStatus(storyTicketNumber, callback) {
https.get('https://username.atlassian.net/rest/api/latest/issue/' + storyTicketNumber, function (res) {
res.on('data', function(data) {
callback(null, data.toString());
});
res.on('error', function(error) {
callback(error);
});
})
}
This single test is passing and I don't understand why. It seems like it is actually doing a real call and not using my fake nock request/response. If I comment the nock section or change:
.reply(200, getIssueResponse) to .reply(404)
It doesn't break the test and nothing change, I'm not doing anything with my nock variable. Can someone please explain me with a clear example how to mock the request and response in my NodeJS http-client using Nock?