Issue
I'm mocking a custom hook and while I'm able to do it with static data at the top of my test file in jest, I want to be able to do it on a per test bases. For eample on each test I want to be able to return different mock data. How would I go about restructuring this yo allow for returning different data on each test.
const mocked_StartCapture= jest.fn()
jest.mock('@myModules/screen-hook', () => ({
...(jest.requireActual('@myModules/screen-hook') as any),
useScreenHook: () => ({
startCapture: () => mocked_StartCapture,
viewableData: () => ({
height: 1500,
width: 1600,
image:
'00w0KGgoAAAANSUhEUgAAAGQiVBORAAABkBAMAAACCzIhnAAAAG1BMVEWJiob',
}),
}),
}))
test('renders Component', async () => {
/// Update mock to use different startCapture and viewableData functions.
const result = render(<Screen/>)
expect(result).toBeDefined()
})
Solution
You can try sth like this:
cosnt mockViewableData = jest.fn.mockReturnValue({
height: 1500,
width: 1600,
image: '00w0KGgoAAAANSUhEUgAAAGQiVBORAAABkBAMAAACCzIhnAAAAG1BMVEWJiob',
}));
const mockStartCapture = jest.fn();
jest.mock('@myModules/screen-hook', () => ({
...(jest.requireActual('@myModules/screen-hook') as any),
useScreenHook: () => ({
startCapture: () => mockStartCapture(),
viewableData: () => mockViewableData(),
}),
}));
And then in tests:
test('renders Component', async () => {
/// Update mock to use different startCapture and viewableData functions.
mockStartCapture.mockReturnValue({ whatever: "you need" });
mockViewableData.mockReturnValue({ height: 42, width: 42, image: 'something' });
const result = render(<Screen/>)
expect(result).toBeDefined()
})
Answered By - Marek Rozmus
Answer Checked By - - Robin (ReactFix Admin)