How to spy to unexported functions which are written inside a function component using JEST?
const ProfilePage: NextPage<Props> = ({
const getUser = () => {
return {
name: 'Joker',
}
}
return (
<Box>Hello world</Box>
)
)}
I want to spy the getUser function and see does it return {name: 'Joker'}
or not. I tried to use enzyme but that won't work for me because it is not available for version 18 of react.
it('GetUserSpy', () => {
jest.spyOn(ProfilePage.prototype,'getUser') // prototype is undefined because its a function component
});
Unfortunately you cannot do this. But you could simply extract your function from your component and export it. If you don't use any hooks in your function that should not be a problem.
Also note that the idea of spying is not checking the returnValue. If you want to see what the getUser function returns, you can simply call it in your test and use expect(result).toBe({name: 'Joker'})
for this you'll also need to export the function. If you do want to spy, this should work:
export const getUser = () => ({
name: 'Joker',
})
const ProfilePage: NextPage<Props> = ({
const user = getUser()
return (
<Box>Hello world</Box>
)
)}
import * as getUserModule from 'path/to/module';
describe('ProfilePage', () => {
it ('should call getUserSpy', () => {
//GIVEN
const getUserSpy = jest.spyOn(getUserModule,'getUser')
//WHEN
render(<ProfilePage />)
//THEN
expect(getUserSpy).toHaveBeenCalled();
})
})