Last active
October 11, 2024 15:30
-
-
Save Danetag/31982ad8d03afbc01042e3678445fd1c to your computer and use it in GitHub Desktop.
Testing a React hook with a redux store
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you!!!