Skip to content

Instantly share code, notes, and snippets.

@mattiaerre
Created December 9, 2018 00:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattiaerre/da3fe3f01504bb5e2e481a16dafb96f4 to your computer and use it in GitHub Desktop.
Save mattiaerre/da3fe3f01504bb5e2e481a16dafb96f4 to your computer and use it in GitHub Desktop.
How to mock a module that exports a factory function with Jest
import fetch from 'node-fetch';
function makeMenusClient(context) {
return {
getMenus: async rid =>
fetch(`${context.menusBaseUrl}/${rid}`)
.then(response => response.json())
.then(json => json)
};
}
export default makeMenusClient;
import makeMenusClient from './makeMenusClient';
async function makeRestaurantDetails(context, options) {
const menusClient = makeMenusClient(context);
const menus = await menusClient.getMenus(options.rid);
return {
menus,
name: options.name,
rid: options.rid
};
}
export default makeRestaurantDetails;
import makeMenusClient from './makeMenusClient';
import makeRestaurantDetails from './makeRestaurantDetails';
jest.mock('./makeMenusClient', () => {
// check: https://stackoverflow.com/a/51534326/752391
const mockMenusClient = { getMenus: jest.fn() };
return jest.fn(() => mockMenusClient);
});
test('makeRestaurantDetails', async () => {
const context = {
menusBaseUrl: 'http://menus.opentable.com/api/v1'
};
const options = {
name: 'Urban Remedy',
rid: 8
};
makeMenusClient().getMenus.mockImplementation(() => [
{ title: 'Brunch' },
{ title: 'Dinner' }
]);
expect(await makeRestaurantDetails(context, options)).toMatchSnapshot();
});
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`makeRestaurantDetails 1`] = `
Object {
"menus": Array [
Object {
"title": "Brunch",
},
Object {
"title": "Dinner",
},
],
"name": "Urban Remedy",
"rid": 8,
}
`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment