Skip to content

Instantly share code, notes, and snippets.

@jsdf
Last active August 30, 2020 20:02
Show Gist options
  • Save jsdf/5388ed42e365aa1a1e1b to your computer and use it in GitHub Desktop.
Save jsdf/5388ed42e365aa1a1e1b to your computer and use it in GitHub Desktop.
Writing and testing async JS with Jest, promises and async functions
jest.dontMock('../getStuff');
describe('getStuff', () => {
let getStuff;
let request;
let stuffStore;
it('loads the data', () => {
const id = 1;
const data = {a: 1};
stuffStore = require('../stuffStore');
request = require('request');
// mock request() to return a promise resolving to a mocked response
// object, which has a method called .json(), which returns a promise
// resolving to the data object.
request.mockImpl(() => {
return Promise.resolve({
json: () => Promise.resolve(data),
});
});
getStuff = require('../getStuff');
// kick off the request
getStuff(id);
// resolve all promises
jest.runAllTimers();
// make assertions about what should have occurred
expect(stuffStore.startLoading).toBeCalledWith(id);
expect(stuffStore.loaded).toBeCalledWith(id, data);
expect(stuffStore.failedLoading).not.toBeCalled();
});
})
// async function based version
import request from 'request';
import stuffStore from './stuffStore';
export default async function getStuff(id) {
stuffStore.startLoading(id);
try {
const res = await request('/stuff/'+id);
const data = await res.json();
stuffStore.loaded(id, data)
} catch (err) {
if (!err instanceof request.RequestError) throw err;
stuffStore.failedLoading(id, err);
}
}
// synchronous version which would block the browser while waiting for data
import request from 'request';
import stuffStore from './stuffStore';
export default function getStuff(id) {
stuffStore.startLoading(id);
try {
const res = request('/stuff/'+id);
const data = res.json();
stuffStore.loaded(id, data)
} catch (err) {
if (!err instanceof request.RequestError) throw err;
stuffStore.failedLoading(id, err);
}
}
// promise based version
import request from 'request';
import stuffStore from './stuffStore';
export default function getStuff(id) {
stuffStore.startLoading(id);
request('/stuff/'+id)
.then(res => res.json())
.then(data => {
stuffStore.loaded(id, data)
})
.catch(err => {
if (!err instanceof request.RequestError) return Promise.reject(err);
stuffStore.failedLoading(id, err);
});
}
const stuffStore = {
startLoading(id) {
},
loaded(id, data) {
},
failedLoading(id, err) {
},
}
export default stuffStore;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment