Nock正在拦截我的请求,但我的AJAX请求错误

时间:2017-01-17 20:10:06

标签: javascript ajax xmlhttprequest nock

我正在测试使用XMLHttpRequest生成的AJAX请求:

export default function requestToTest() {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', 'https://example.com/service');

  xhr.onload = () => {
    console.log('onload');
    // etc.
  };

  xhr.onerror = () => {
    console.log('onerror');
    // etc.
  };

  xhr.send();
}

所以我使用Nock(和Mocha)设置了一个测试:

describe('requestToTest()', () => {
  it('should handle a successful request', () => {
    nock('https://example.com')
      .log(console.log)
      .get('/service')
      .reply(200, { some: 'json' });

    requestToTest();

    expect( /* things I want to check */ ).to.be.true;
  });
});

当我运行此测试时,xhr.onerror()会触发,而不是xhr.onload()。但是,通过观察Nock的调用log()的输出,我确信Nock正在拦截我的AJAX请求,截获的请求与Nock的预期URL匹配。

为什么在我的测试中调用xhr.onerror而不是xhr.onload

1 个答案:

答案 0 :(得分:1)

作为一种解决方法,我使用了isomorphic-fetch库。该库是var eTemplate = require('./template.model'); export function create(req, res) { console.log(req.body); eTemplate.createAsync(req.body) .then(responseWithResult(res, 201)) .catch(handleError(res)); } 用于发出AJAX请求的替代方法,并且明确地设计为在浏览器环境和Node.js /测试环境中或多或少地相同地工作。

通常,使用一个旨在消除浏览器中的AJAX请求之间的差异并从测试环境发出请求的库似乎是解决此问题的方法。