Mock custom hook from 3rd party library in Jest - reactjs

I am using a custom hook from 3rd party library in my React project:
import { useProductData } from '#third/prod-data-component';
const ProductRow: React.FC<MyProduct> = ({ product }) => {
// using the custom hook here
const productData = useProductData();
})
The signature of that hook function is:
export declare const useProductData: () => string | undefined;
In my jest test, I would like to mock the returned value of the hook, I tried:
it('should show correct product data', ()=>{
jest.mock('#third/prod-data-component', () => {
return { useProductData: jest.fn(()=>'foo')}
});
...
...
})
When I run test, the above mock doesn't take any effect.
How to mock the return value of custom hook that is from a 3rd party library?
==== UPDATE ====
I also tried this:
jest.mock('#third/prod-data-component', () => {
const lib = jest.requireActual('#third/prod-data-component');
return {...lib, useProductData: () => 'foo'}
});
But does't work either.

can you try this
import {useProductData} from '#third/prod-data-component'
jest.mock('#third/prod-data-component');
(useProductData as jest.Mock).mockImplementation(() => {mockKey: 'mockData'})
describe('test scenario', () => {
it('should show correct product data', () => {
// your assertions
})
})

Reading your example, you may be missing the actual module import.
However, have you tried the full module mocking?
import moduleMock from '#third/prod-data-component'
jest.mock('#third/prod-data-component')
describe('test scenario', () => {
it('should show correct product data', () => {
moduleMock.useProductData.mockReturnValue(...)
})
})
EDIT
I missed the Typescript part. You need to wrap the actual module type definitions with Jest's own type definitions.
I solved this problem in the past in the following way, using jest.mocked function:
import prod_data_component_module from '#third/prod-data-component'
jest.mock('#third/prod-data-component')
describe('Your test case scenario', () => {
const mock = jest.mocked(prod_data_component_module, { shallow: true })
it('Your test here', async () => {
mock.useProductData.mockReturnValue('...')
// test logic here
})
})
mock is a jest wrapper of the original module. It is of type jest.MockedFn<T>, so it contains actual exported types/functions and also jest mocks.

Related

jest - react - mocked geolocation inside useEffect in hook

how would you test a hook that is using navigator.geolocation.getCurrentPosition() method (mocked it already based on this: https://newdevzone.com/posts/how-to-mock-navigatorgeolocation-in-a-react-jest-test) in useEffect?
I can't see the way how to wait for result as upon calling the function it does not return anything and returned data are processed in passed callback. found some hackish solution that works when run debug using jest runner vsc extension, but does not for regular test run.
the hook:
const useGeolocation = () => {
const [coords, setCoords] = useState<GeolocationCoordinates>();
useEffect(() => {
navigator.geolocation.getCurrentPosition((position) => {
setCoords(position.coords);
});
}, []);
return coords;
};
test:
import { renderHook } from '#testing-library/react';
it('should return non-empty coords', async () => {
const { result } = renderHook(() => useGeolocation());
// MISSING CODE
expect(result.current).not.toBe(undefined);
});
I'll be happy for any idea leading to solution so I don't need to give up on unit testing once again :slight_smile:

Jest to test a class method which has inner function

I'm writing unit test for once of my .ts file. Where I'm facing a problem and unable to find the solution. Hopefully someone can help me to resolve it.
Problem
While writing unit test. I'm unable to test the value for profile. After calling a method called getProfile().
File setup
Profile.ts
import { getProfileAPI} from "./api";
class ProfileDetails implements IProfileDetails {
public profile: string = ''
constructor() {}
getProfile = async () => {
const { data } = await getProfileAPI();
if (data) {
this.profile = data
}
};
}
const profileDetail = new ProfileDetails();
export default profileDetail;
Profile.spec.ts
import Profile from './Profile';
describe('Profile', () => {
it('getProfile', async () => {
Profile.getProfile = jest.fn();
await Profile.getProfile();
expect(Profile.getProfile).toHaveBeenCalled();
});
});
So the challenge I'm facing here is, I can able to mock the getProfile method. But I'm not able to mock the getProfileAPI function which is called inside the getProfile method.
How can I mock a function which is called inside a mocked method (or) is there any other way to resolve this. Kindly help.
Thanks in advance.
Before answering your questions, I may have some comments :
your test is wrong, all it does is calling the method then checking if it is called, of course it will always pass !
you are not really mocking, in fact you're erasing the old method and it may have some impacts on other tests.
your method "getProfile" should be called "getAndSetProfile", or "syncProfile", or something like that, getProfile is confusing for a developer, he will think it only get the profile and returns it.
I don't recommend creating & exporting an instance of ProfileDetails like this, you should take a look on DI (Dependency Injection) with typedi for example.
Do not forget :
A unit test means that any dependency inside your "unit" should be mock, you must only test the logic inside your "unit" (in your case, the getProfile function, or the class itself).
Here, you are invoking a method called "getProfileAPI" from another service that is not mocked, so you are currently testing its logic too.
This test should work :
Profile.spec.ts
jest.mock('./api', () => ({
getProfileAPI: jest.fn(),
}));
import { getProfileAPI } from "./api";
import Profile from './Profile';
describe('Profile', () => {
it('getProfile', async () => {
await Profile.getProfile();
expect(getProfileAPI).toHaveBeenCalled();
});
});
In our example, Profile.profile will be empty, because even if we mocked to getProfileAPI method, we didn't make it return something. You could test both cases :
jest.mock('./api', () => ({
getProfileAPI: jest.fn(),
}));
import { getProfileAPI } from "./api";
import Profile from './Profile';
const mockGetProfileAPI = getProfileAPI as jest.Mock; // Typescript fix for mocks, else mockResolvedValue method will show an error
describe('Profile', () => {
describe('getProfile', () => {
describe('with data', () => {
const profile = 'TEST_PROFILE';
beforeEach(() => {
mockGetProfileAPI.mockResolvedValue({
data: profile,
});
});
it('should call getProfileAPI method', async () => {
await Profile.getProfile();
expect(mockGetProfileAPI).toHaveBeenCalled(); // Please note that "expect(getProfileAPI).toHaveBeenCalled();" would work
});
it('should set profile', async () => {
await Profile.getProfile();
expect(Profile.profile).toBe(profile);
});
});
describe.skip('with no data', () => {
it('should not set profile', async () => {
await Profile.getProfile();
expect(Profile.profile).toStrictEqual(''); // the default value
});
});
});
});
NB : I skipped the last test because it won't work in your case. Profile isn't recreated between tests, and as it is an object, it keeps the value of Profile.profile (btw, this is a bit weird) between each tests. This is one of the reasons why you should not export a new instance of the class.

Make sure function from React.useContext is called in Jest

Given a custom hook that looks like this:
const getSavedInfo (id) => {
const endpoint = getEndpoint(id)
const {updateInfo} = React.useContext(infoContext)
axios.get(endpoint).then((res) => {
if (res) {
updateInfo(res.data)
}
})
}
How would I go about properly mocking the updateInfo method so I can make sure it was called within my jest test?
You need to pass the provider in test while rendering the custom hook. You can write your own provider function or use react-hooks-testing-library which does the same thing for you. Like this:
import { renderHook } from 'react-hooks-testing-library';
const wrapper = ({ children }) => (
<InfoContext.Provider value={{updateInfo: jest.fn}}>{children}</InfoContext.Provider>
);
it('should call update info', () => {
const { result } = renderHook(() => getSavedInfo(), { wrapper });
// rest of the test code goes here
});
You can find detailed explanation here

How to use jest.spyOn with react testing library

I'm refactoring a class component to a funcional component.
In my test file i was using enzyme, but i'm migrating to react-testing-library
This the test i'm doing using enzyme
it('should change module when clicked button login', () => {
const wrapper = mount(<SignUp setModuleCallback={jest.fn()} />)
const instance = wrapper.instance()
jest.spyOn(instance, 'setModule')
wrapper.find('button#login-button').simulate('click')
expect(instance.setModule).toHaveBeenCalled()
})
And this is what i'm trying to do using react-testing-library
it('should change module when clicked button login', async () => {
const { getByTestId } = render(<SignUp setModuleCallback={jest.fn()} />)
const instance = getByTestId('submit')
jest.spyOn(instance, 'setModule')
const button = await waitFor(() => getByTestId('submit'))
act(() => {
fireEvent.click(button)
})
expect(instance.setModule).toHaveBeenCalled()
})
Here's the error that i'm getting
The philosophy behind RTL is that you should test your components "the way your software is used." With that in mind, is there a way to test your component without explicitly asserting that the callback was invoked?
According to your test name, you expect some "module to change." Is there some way to verify in the DOM that the module was changed? For example, maybe each "module" has a unique title, in which case you could use screen.getByText to assert that the correct module is rendered after clicking the button.
If you want to explicitly assert that a callback function was invoked, are you sure you have to use spyOn for this test? I would try something like this:
it('should change module when clicked button login', async () => {
const mockCallback = jest.fn()
const { getByTestId } = render(<SignUp setModuleCallback={mockCallback} />)
const button = await waitFor(() => getByTestId('submit'))
act(() => {
fireEvent.click(button)
})
expect(mockCallback).toHaveBeenCalled()
})

How can we test the return type of method by using sinon.spy?

We are using the sinon to test our api call in reactjs application Like this:-
import * as Actions from 'routes/actions/Actions';
const requestAction = {
RequestShell() { Actions.request(); },
};
describe('testing for Actions', () => {
it('check whether request() method call is happening properly or not', () => {
const requestData = sinon.spy(requestAction, 'RequestShell');
requestAction.RequestShell();
sinon.assert.calledOnce(requestData);
requestData.restore();
});
Now I need to compare if Actions.request() return type is Json object or not. How can I test the return type of the action by using sinon? Please assist me.
Try with this
JS
it('check whether request() method call is happening properly or not', () => {
const requestData = sinon.spy(requestAction, 'RequestShell');
requestAction.RequestShell();
assert(requestData.calledOnce);
requestAction.RequestShell.restore();
});
refer this linksinon spies

Resources