最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Testing XHR with Jest - Stack Overflow

programmeradmin3浏览0评论

I have this simple test case:

describe ('Request', function () {
  it ('should perform a XHR "GET" request', function (done) {
    var xhr = new XMLHttpRequest;

    xhr.open('GET', '', true);
    xhr.send();
  });
});

The point is: when I do jest in my terminal, seems it's not requesting . I think this is happening because Jest uses jsdom under the hood and it haven't capability to reproduce an HTTP request out of the browser itself.

Suggestions?

Note: any errors are appearing, the test is passing, but the request isn't being made.

I have this simple test case:

describe ('Request', function () {
  it ('should perform a XHR "GET" request', function (done) {
    var xhr = new XMLHttpRequest;

    xhr.open('GET', 'http://google.', true);
    xhr.send();
  });
});

The point is: when I do jest in my terminal, seems it's not requesting http://google.. I think this is happening because Jest uses jsdom under the hood and it haven't capability to reproduce an HTTP request out of the browser itself.

Suggestions?

Note: any errors are appearing, the test is passing, but the request isn't being made.

Share Improve this question asked Mar 20, 2015 at 21:55 Guilherme OderdengeGuilherme Oderdenge 5,0116 gold badges66 silver badges96 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

I'm assuming you are not looking to do unit testing but are intending to create an integration test of some kind or that you want to write tests for the API you are calling.

In both cases you are going to have to supply the global scope with the XMLHttpRequest object as it does not exist in node js (the platform where your test code is running)

You can do this by installing this package: https://www.npmjs./package/xmlhttprequest

And then running this code before any of your tests:

global.XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

You can also not use jest for this purpose and go with chakram or frisby, both are built for API testing and both take care of making the request for you.

There're a number of problems:

  1. In your code example you don't create instance of XMLHttpRequest. It should be look like this: var xhr = new XMLHttpRequest()
  2. Making real requests in tests is a bad idea. If your module depends on data from remote server you should mock XMLHttpsRequest or use "fake server" (e.g. sinon). I strongly remend you don't make real requests in tests.
发布评论

评论列表(0)

  1. 暂无评论