简体   繁体   English

Nock正在拦截我的请求,但是我的AJAX请求出错了

[英]Nock is intercepting my request, but my AJAX request is erroring out

I'm testing an AJAX request made using XMLHttpRequest : 我正在测试使用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();
}

So I set up a test using Nock (and Mocha): 因此,我使用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;
  });
});

When I run this test, xhr.onerror() fires, not xhr.onload() . 当我运行此测试时, xhr.onerror()触发xhr.onerror() ,而不触发xhr.onload() However, from observing Nock's output from the call to log() , I know for certain that Nock is intercepting my AJAX request and that the intercepted request matches Nock's expected URL. 但是,通过观察对log()的调用得出的Nock输出,我可以肯定地知道Nock正在拦截我的AJAX请求,并且所拦截的请求与Nock的预期URL相匹配。

Why is xhr.onerror being called instead of xhr.onload in my test? 为什么在测试中调用xhr.onerror而不是xhr.onload

As a workaround, I used the isomorphic-fetch library. 解决方法是,我使用了同构提取库。 This library is an alternative to XMLHttpRequest for making AJAX requests and is expressly designed to work more or less identically in browser environments and in Node.js/test environments. 该库是XMLHttpRequest提出AJAX请求的替代方法,并且明确设计为在浏览器环境和Node.js / test环境中或多或少地工作。

In general, using a library designed to smooth out the differences between AJAX requests in the browser and making a request from the testing environment seems like the solution to this problem. 通常,使用旨在缓解浏览器中AJAX请求之间的差异以及从测试环境发出请求的库似乎是解决此问题的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM