I have a custom hook as below
export const useUserSearch = () => {
const [options, setOptions] = useState([]);
const [searchString, setSearchString] = useState("");
const [userSearch] = useUserSearchMutation();
useEffect(() => {
if (searchString.trim().length > 3) {
const searchParams = {
orgId: "1",
userId: "1",
searchQuery: searchString.trim(),
};
userSearch(searchParams)
.then((data) => {
setOptions(data);
})
.catch((err) => {
setOptions([]);
console.log("error", err);
});
}
}, [searchString, userSearch]);
return {
options,
setSearchString,
};
};
and I want to test this hook but am not able to mock userSearch
function which is being called inside useEffect.
can anybody help?
this is my test
it('should set state and test function', async () => {
const wrapper = ({ children }) => (
<Provider store={store}>{children}</Provider>
)
const { result } = renderHook(
() => useUserSearch(),
{ wrapper }
)
await act(async () => {
result.current.setSearchString('abc5')
})
expect(result.current.options).toEqual(expected)
})
useUserSearchMutation
import {createApi, fetchBaseQuery} from '@reduxjs/toolkit/query/react';
export const userSearchAPI = createApi({
reducerPath: 'userSearchResult',
baseQuery: fetchBaseQuery({baseUrl: process.env.REACT_APP_BASE_URL}),
tagTypes: ['Users'],
endpoints: build => ({
userSearch: build.mutation({
query: body => ({url: '/org/patient/search', method: 'POST', body}),
invalidatesTags: ['Users'],
}),
}),
});
export const {useUserSearchMutation} = userSearchAPI;
useUserSearch
is the first item in an array returned fromuseUserSearchMutation
. So have you tried mockinguseUserSearchMutation
as follows:jest.mock('./useUserSearchMutation'., () => [jest.fn(() => ['mock-data']])
– Servomechanismexport const { useUserSearchMutation } = userSearchAPI
@Servomechanism – AfricanizeuseUserSearchMutation
hook – Mcginnisimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react' export const userSearchAPI = createApi({ reducerPath: 'userSearchResult', baseQuery: fetchBaseQuery({ baseUrl: process.env.REACT_APP_BASE_URL }), tagTypes: ['Users'], endpoints: (build) => ({ userSearch: build.mutation({ query: (body) => ({ url:
/org/patient/search, method: 'POST', body, }), invalidatesTags: ['Users'], }), }), }) export const { useUserSearchMutation } = userSearchAPI
– Africanize