I develop a nodejs app which get url and send a response (json or xml) depending on parameters in url (I've to develop POST and GET/POST with SOAP). But I see somes mock modules like nock & I ask myself, what are the benefits of these modules compared to my own app ?
example of my code :
app.get('/uri/to/call/', function(req, res) {
if(req.query.username=='John'){
res.json(passedMock);
}else{
res.json(failedMock);
}
})
The benefits of a network mocking library, such as Nock, come into play when your app is making outbound HTTP calls while handling inbound requests.
Imaging a basic app that looked like this, it gathers data from a third party before responding:
app.get('/uri/to/call/', function(req, res) {
http.get('http://some.third.party.example.com', dataResp => {
// process data in some way
resp.json(data)
}
})
Now there are many different kinds of tests you can/should write to test this app, but one category of tests would include how your app respondes and handles errors without actually calling the third party's API while your tests are running.
Sticking with Nock, you could write a that test confirms your app handles an error from the third party by first mocking the internal request, like so:
nock('http://some.third.party.example.com')
.get('/')
.replyWithError('oh no!')
Then calling your app and asserting against the response.
And this type of test isn't only for error cases. There are lots of reasons why it would not be ideal to hit the third party during your tests.