Created
January 21, 2022 13:56
-
-
Save scriptex/9c8235552c4e01d9c7e5d626555c690a to your computer and use it in GitHub Desktop.
A helper to test custom hooks with react-testing-library
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 * as React from 'react'; | |
import thunk from 'redux-thunk'; | |
import { render } from '@testing-library/react'; | |
import { Router } from 'react-router'; | |
import { Provider } from 'react-redux'; | |
import configureMockStore from 'redux-mock-store'; | |
// remember to import your history object | |
// store is your redux store | |
export type RootState = ReturnType<typeof store.getState>; | |
export type UnknownFunction = (...args: unknown[]) => unknown; | |
interface Props { | |
state: Partial<RootState>; | |
children: any; | |
withRouter?: boolean; | |
} | |
export const TestStoreProvider: React.FC<Readonly<Props>> = ({ | |
state, | |
children, | |
withRouter, | |
}: Props) => ( | |
<Provider store={configureMockStore([thunk])(state)}> | |
{withRouter ? <Router history={history}>{children}</Router> : children} | |
</Provider> | |
); | |
export const hookTest = <T extends UnknownFunction>( | |
hook: T, | |
state: RootState, | |
...args: Parameters<T>[] | |
): ReturnType<T> => { | |
const returnValue = {} as ReturnType<T>; | |
const TestComponent: React.FC = () => { | |
Object.assign(returnValue, hook.apply(null, ...args)); | |
return null; | |
}; | |
render( | |
<TestStoreProvider state={state} withRouter> | |
<TestComponent /> | |
</TestStoreProvider>, | |
); | |
return returnValue; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment