Created
December 9, 2018 00:27
-
-
Save mattiaerre/da3fe3f01504bb5e2e481a16dafb96f4 to your computer and use it in GitHub Desktop.
How to mock a module that exports a factory function with Jest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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