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 badges2 Answers
Reset to default 4I'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:
- In your code example you don't create instance of XMLHttpRequest. It should be look like this:
var xhr = new XMLHttpRequest()
- 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.