Skip to content

Instantly share code, notes, and snippets.

@crccheck
Last active August 29, 2015 14:20
Show Gist options
  • Save crccheck/eb7edc88d80ef28825f0 to your computer and use it in GitHub Desktop.
Save crccheck/eb7edc88d80ef28825f0 to your computer and use it in GitHub Desktop.
Isomorphic Ajax.js hell

Picking a testable ajax library for react (using jest)

Here are some examples of doing a GET request against a resource and getting JSON back.

jQuery

Works. Works great. It just brings along a lot of baggage you won't need in a ReactJS app. Removing jQuery will remove over 200KB (unminified/gzipped).

Fetch

The only fetch implementation that's testable is isomorphic-fetch. It's designed after the official WHATWG spec.

A new package that's inspired by request (sp). It's simple but still very new. It has shortcuts for constructing querystrings and request bodies, but you have to get json out of the response yourself. You also have to handle errors yourself.

Other alternatives

// app.js
import fetch_ from 'isomorphic-fetch';
// HACK for "Uncaught TypeError: Illegal invocation" error in Chrome
// https://github.com/matthew-andrews/isomorphic-fetch/pull/20/files
var fetch = fetch_.bind(undefined);
fetch(url)
.then((response) => response.json())
.then((data) => {
this.setState(...);
})
.catch((ex) => {
console.log('fetch failed', ex);
})
// tests.js
var fetch = require('isomorphic-fetch');
fetch.mockReturnValue({
'then': (responseCB) => {
return {'then': (dataCB) => {
dataCB(response); // execute the `done` callback immediately
return {
'catch': (exceptionCB) => {};
}
}
}
});
// app.js
import $ from 'jquery';
$.getJSON(url)
.done((data, textStatus, jqXHR) => {
this.setState(...);
})
.fail((jqXHR, textStatus, errorThrown) => {
console.log('getJSON failed', textStatus);
})
// tests.js
var mockPromise = jest.genMockFunction();
var successfulAjaxPromis = {fail: () => {});
mockPromise.mockReturnValue({
'done': (callback) => {
callback(response); // execute the `done` callback immediately
return successfulAjaxPromise;
},
});
$.getJSON = mockPromise;
// app.js
import request from 'then-request';
request('GET', url)
.then((response) => {
var data = JSON.parse(response.body);
this.setSTate(...);
});
// tests.js
var request = require('then-request');
request.mockReturnValue({
'then': (dataCB) => {
dataCB(response); // execute the `done` callback immediately
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment