在路由中间谍/存根请求(通过chai.request)

时间:2016-11-18 01:47:36

标签: testing mocha sinon chai

问题

我有一个名为/players的端点,它向外部服务器发出http请求,我不希望在我的测试中执行该请求,但我无法弄清楚如何在这种情况。

代码

test/controllers/test-players.js

// ...

it('returns all players', done => {
  chai.request(app) // the content of app is not relevant
    .get('/players')
    .end((err, res) => {
      expect(err).to.not.exist
      expect(res.body.length).to.equal(3)

      done()
    })
})

// ...

controllers/players.js

const request = require('request')

module.exports = (req, res) => {
  request('http://externalendpoint.com', (error, request, body) => {
    res.json(body)
  })
}

详细

我正在使用:

  • 节点(v6)
  • Express(v4)
  • 摩卡(v3)
  • 柴(v3)
  • Sinon(v1.17)

想法?

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。我刚刚使用nock拦截了请求:

const fixture = [{id: 1, name: 'User'}, {id: 2, name: 'Admin'}, {id: 3, name: 'Subadmin'}]

nock('https://domain.com')
  .get('/some-endpoint')
  .reply(200, {fixture})

it('returns all players', done => {
  chai.request(app) // the content of app is not relevant
    .get('/players')
    .end((err, res) => {
      expect(err).to.not.exist
      expect(res.body.length).to.equal(3)

      done()
    })
})