Search code examples
javascriptnode.jschainockhttp-mock

Testing async code in catch block using Nock or httpMock


I making a axios request which fails and throws error in catch block. In catch block I am making request to other end point to get results

router.get('/info', (req, res) => {
  axios('www.getInformationApi.com')
    .then(results => {
      return res.status(200).json(results.data);
    })
    .catch(async(err) => {

      if (err === 'server_down') {
        try {
          // need to improve test coverage for this lines
          const secondsResults = await axios('www.getInformationApi2.com');
          return res.status(200).json(secondsResults)
        } catch (error) {
          throw Error(error)
        }
      } else {
        const error = errors.createEntError(err.message, errorList);
        return res.status(constants.HTTP_SERVER_ERROR).json(error);
      }


    })

});

I like to write Unit test which covers "Axios" request in catch block using "nock" or "http-mocks"

Can I able to test using Unit test or do I need to run integration tests in this scenario


Solution

  • According to answer about good unit test, there is a statement that:

    Don't test code that you don't own

    So, in case you're using nock or http-mocks your test is dependent on axios library as well. Because if axios have a bug - your test might show it up. So, from my view more correctly to mark it as integration test then.

    Good unit test should be independent, and what comes down - axios library should be stubbed, with behavior you wanna test, i.e.:

    sinon.stub(axios, 'get').rejects('server_down')