使用Nock和Request模拟HTTP请求错误

gor*_*lph 3 mocking request node.js

我在一个当前没有测试过的函数中有一个分支.它是来自request操作的错误处理程序(使用同名的节点模块).这是特定的行:

request(url, function (error, response, body) {
  if (error) return cb(error);
Run Code Online (Sandbox Code Playgroud)

这是测试:

  describe("handles errors", function() {
    it("from the request", function (done) {
    var api = nock('http://football-api.com')
                .get('/api/?Action=today&APIKey=' + secrets.APIKey + '&comp_id=1204')
                .reply(500);

    fixture.getFixture(FixtureMock, function (err, fixture) {
      expect(err).to.exist
      done();
    });
  });
Run Code Online (Sandbox Code Playgroud)

规格失败:

Uncaught AssertionError: expected null to exist
Run Code Online (Sandbox Code Playgroud)

因此,将500状态代码作为没有正文的响应发送不会导致error请求回调,或者我正在测试错误的东西.

小智 7

使用replyWithError来自doc:

nock('http://www.google.com')
   .get('/cat-poems')
   .replyWithError('something awful happened');
Run Code Online (Sandbox Code Playgroud)