XMLHttpRequest testing in Jest

The jest api has changed a bit. This is what I use. It doesn’t do anything but it’s enough to render my components. const xhrMockClass = () => ({ open : jest.fn(), send : jest.fn(), setRequestHeader: jest.fn() }) window.XMLHttpRequest = jest.fn().mockImplementation(xhrMockClass) and in the test file: import ‘../../__mock__/xhr-mock.js’

Cross-domain XMLHttpRequest using background pages

You don’t have to mess with iframes. It’s possible to perform cross-domain XMLHttpRequests, using background pages. Since Chrome 13, cross-site requests can be made from the content script. However, requests can still fail if the page is served with a Content Security Policy header with a restricting connect-src. Another reason for choosing the nexy method … Read more

XHR request URL says does not exist when attempting to parse it’s content

You have several problems: the url should be http://www.whoscored.com/stageplayerstatfeed wrong GET parameters missing important required headers you need response.json(), not response.body The fixed version: import requests url=”http://www.whoscored.com/stageplayerstatfeed” params = { ‘field’: ‘1’, ‘isAscending’: ‘false’, ‘orderBy’: ‘Rating’, ‘playerId’: ‘-1’, ‘stageId’: ‘9155’, ‘teamId’: ’32’ } headers = {‘User-Agent’: ‘Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, … Read more

XmlHttpRequest.responseText while loading (readyState==3) in Chrome

Chrome has a bug where it will only populate xhr.responseText after a certain number of bytes has been received. There are 2 ways to get around this, Set the content type of the return to “application/octet-stream” or Send a prelude of about 2kb to prep the handler. Either of these methods should make chrome populate … Read more

Adding X-CSRF-Token header globally to all instances of XMLHttpRequest();

I’d recommend to intercept calls to the send method: (function() { var send = XMLHttpRequest.prototype.send, token = $(‘meta[name=csrf-token]’).attr(‘content’); XMLHttpRequest.prototype.send = function(data) { this.setRequestHeader(‘X-CSRF-Token’, token); return send.apply(this, arguments); }; }()); This won’t add the header at instantiation time, but right before the request is sent. You can intercept calls to new XMLHttpRequest() as well, but that … Read more