Skip to content

Instantly share code, notes, and snippets.

@scriptex
Created January 21, 2022 13:56
Show Gist options
  • Save scriptex/9c8235552c4e01d9c7e5d626555c690a to your computer and use it in GitHub Desktop.
Save scriptex/9c8235552c4e01d9c7e5d626555c690a to your computer and use it in GitHub Desktop.
A helper to test custom hooks with react-testing-library
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