【问题标题】:Nock is intercepting my request, but my AJAX request is erroring outNock 正在拦截我的请求,但我的 AJAX 请求出错了
【发布时间】:2017-01-17 20:10:05
【问题描述】:

我正在测试使用 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

【问题讨论】:

  • 我从来没有完全弄清楚这一点,但我认为这是因为XMLHttpRequest 仅在浏览器环境中定义,而不是在 Node.js 中。

标签: javascript ajax xmlhttprequest nock


【解决方案1】:

作为一种解决方法,我使用了isomorphic-fetch 库。这个库是 XMLHttpRequest 的替代品,用于发出 AJAX 请求,并且明确设计为在浏览器环境和 Node.js/test 环境中或多或少地工作。

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

【讨论】:

    猜你喜欢
    • 2016-10-05
    • 2019-07-14
    • 2019-09-26
    • 2019-09-19
    • 2017-06-19
    • 1970-01-01
    • 2013-05-24
    • 1970-01-01
    • 2011-12-26
    相关资源
    最近更新 更多