'React router - useOutletContext testing
I'm using react-router V6 and trying to test the new feature of useOutletContext. my testing library is testing-library/react and I'm not sure how to pass the Context data in the test.
In the TSX component, I'm getting the data with the hook of react-router:
const { data } = useOutletContext<IContext>()
I need something like:
test("render outlet context data view", async () => {
const { getByTestId } = render(
<MockedProvider mocks={[mockData]} context={myContextData}>
<ContextDataView />
</MockedProvider>
)
the MockedProvider tag is from @apollo/client/testing
the context={myContextData} part is what i need
Solution 1:[1]
I needed the same thing at work, and one of my colleagues helped me finally figure it out.
in your test file
import * as rrd from 'react-router-dom';
then set up your data just like you'd expect, and use Jest to mock React-router-dom
let mockData = { mock: 'Data' }
jest.mock('react-router-dom');
and then in your test
test("render outlet context data view", async () => {
rrd.useOutletContext.mockReturnValue(mockData)
render(<ContextDataView />)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |