【问题标题】:Testing async code in catch block using Nock or httpMock使用 Nock 或 httpMock 在 catch 块中测试异步代码
【发布时间】:2019-03-07 04:39:27
【问题描述】:

我发出了一个失败的 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”请求的单元测试

我能否使用单元测试进行测试,或者我需要在这种情况下运行集成测试

【问题讨论】:

标签: javascript node.js chai nock http-mock


【解决方案1】:

根据good unit test的回答,有一个说法是:

不要测试不属于你的代码

所以,如果您使用nockhttp-mocks,您的测试也依赖于axios 库。因为如果 axios 有错误 - 您的测试可能会显示它。所以,在我看来,更正确地将其标记为 integration 测试然后。

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

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

【讨论】:

    猜你喜欢
    • 2017-01-26
    • 2012-01-18
    • 2023-04-01
    • 1970-01-01
    • 2023-03-19
    • 2018-06-05
    • 2020-09-13
    • 2011-01-04
    • 1970-01-01
    相关资源
    最近更新 更多