Skip to content

Instantly share code, notes, and snippets.

@Danetag
Last active October 11, 2024 15:30
Show Gist options
  • Save Danetag/31982ad8d03afbc01042e3678445fd1c to your computer and use it in GitHub Desktop.
Save Danetag/31982ad8d03afbc01042e3678445fd1c to your computer and use it in GitHub Desktop.
Testing a React hook with a redux store
import React from 'react';
import { renderHook } from '@testing-library/react-hooks';
import stateFactory from 'jest/stateFactory';
import configureMockStore from 'redux-mock-store';
import { Provider } from 'react-redux';
import { Store, AnyAction } from 'redux';
import { initialState as initialPaginationState } from '../../store/pagination/reducer';
import { useMyAwesomeHook } from '../useMyAwesomeHook';
// Custom wrapper to provide any store to the provider
function getWrapper(store: Store<any, AnyAction>): React.FC {
return ({ children }: { children?: React.ReactNode }) => <Provider store={store}>{children}</Provider>;
}
describe('The useMyAwesomeHook hook', () => {
it('should return a good result', () => {
// creates mock store
const store = configureMockStore()(
stateFactory({
// custom initial states go here
// (should be based on initial state from your reducers)
pagination: {
{ ...initialPaginationState },
page: 1
},
}),
);
// get wrapper
const wrapper = getWrapper(store);
// render the hook with the custom wrapper
const { result } = renderHook(() => useLinkParameters(), { wrapper });
// test result
expect(result.current).toBe('/?page=1');
});
});
@jjmato
Copy link

jjmato commented Sep 15, 2023

Thanks you!!! you make my day 💖

@mkloouo
Copy link

mkloouo commented Feb 6, 2024

The same, thank you so much for that example! ❤️

@chad-fossa
Copy link

THANK YOU!!! <3

@XD-Builder
Copy link

Thank you!!!

@yohanskii
Copy link

Thank you!! 🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment