Search code examples
node.jsmockingmocha.jssinon

How to unit test Request library with mocha sinon stub?


How would I test the NPM Request library with Mocha, sinon and chai? I get an Error: getaddrinfo ENOTFOUND. The URL shouldnt matter as I expect the yields value to return no matter what the 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"}
      })
}

Solution

  • So the answer was that sinon is unable to stub standalone functions, it can only stubs functions where there is a parent e.g. Object.function.

    Can use rewire proxyquire however using Jest test runner instead of mocha feels like a better solution as jest provides more complete out the box functionality which includes mocks and assertions