Last active
December 20, 2022 15:17
-
-
Save CarmeloRicarte/b4e03e0126971954c05ba4b20e0139b8 to your computer and use it in GitHub Desktop.
Render store hook with providers
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, { PropsWithChildren } from "react"; | |
import { renderHook, RenderOptions } from "@testing-library/react"; | |
import { Provider } from "react-redux"; | |
import { ToolkitStore } from "@reduxjs/toolkit/dist/configureStore"; | |
import type { AppStore } from "../../src/store"; | |
// This type interface extends the default options for render from RTL, as well | |
// as allows the user to specify other things such as store. | |
interface ExtendedRenderOptions extends Omit<RenderOptions, "queries"> { | |
store?: AppStore; | |
} | |
export const renderStoreHookWithProviders = ( | |
hook: () => any, | |
mockStore: ToolkitStore, | |
{ | |
// create a store instance | |
store = mockStore, | |
}: ExtendedRenderOptions = {} | |
): { | |
store: AppStore; | |
result: { | |
current: { | |
[key: string]: any; | |
}; | |
}; | |
} => { | |
const Wrapper = ({ | |
children, | |
}: PropsWithChildren<Record<string, unknown>>): JSX.Element => ( | |
<Provider store={store}>{children}</Provider> | |
); | |
const { result } = renderHook(hook, { wrapper: Wrapper }); | |
// Return an object with the store and result of render the hook | |
return { | |
store, | |
result, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment