【问题标题】:How to unit test Request library with mocha sinon stub?如何使用 mocha sinon 存根对请求库进行单元测试?
【发布时间】:2021-11-26 18:37:36
【问题描述】:

如何使用 Mocha、sinon 和 chai 测试 NPM 请求库? 我得到一个Error: getaddrinfo ENOTFOUND。 URL 应该无关紧要,因为我希望 yields 无论 url 是什么值都会返回

describe(`api tests`, () => {
  it(`should return`, async () => {
    sinon.stub(request, `get`).yields(null, null, JSON.stringify({test: `teststub`}))


    return apiFunction.then(res => {
      assert.equal(res.body, {test: "stubtest"})
    })
  })
})



 const apiFunction () => {  
    request(
        {
          url: `http://url`
        },
        (err, response, body) => {
          console.log(body) // should be {test: "subtest"}
      })
}

【问题讨论】:

    标签: node.js mocking mocha.js sinon


    【解决方案1】:

    所以答案是 sinon 无法存根独立函数,它只能存根有父函数的函数,例如对象.函数。

    可以使用 rewire proxyquire 但是使用 Jest 测试运行器而不是 mocha 感觉是一个更好的解决方案,因为 jest 提供了更完整的开箱即用功能,包括模拟和断言

    【讨论】:

      猜你喜欢
      • 2019-05-24
      • 2017-06-05
      • 1970-01-01
      • 2016-05-26
      • 2021-09-27
      • 2023-04-09
      • 2017-06-05
      • 1970-01-01
      • 2016-12-21
      相关资源
      最近更新 更多