使用 Nock 或 httpMock 在 catch 块中测试异步代码

Testing async code in catch block using Nock or httpMock

我发出了一个 axios 请求,它失败并在 catch 块中抛出错误。 在 catch 块中,我正在向其他端点发出请求以获取结果

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);
      }


    })

});

我喜欢使用 "nock" 或 "http-mocks"

编写涵盖 catch 块中 "Axios" 请求的单元测试

在这种情况下,我可以使用单元测试进行测试还是需要 运行 集成测试

根据关于good unit test的回答,有这样的说法:

Don't test code that you don't own

因此,如果您也在使用 nock or http-mocks your test is dependent on axios 库。因为如果 axios 有错误——你的测试可能会显示出来。所以,在我看来更正确的做法是将其标记为 integration test 然后。

好的单元测试应该是独立的,结果是 - axios 库应该是 stubbed,具有您想测试的行为,即:

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