S
SolidJS14mo ago
driechel

Test component with useContext

I have a component that has useContext() to ask for a context which is created all the way at the top in index.tsx. When I only render the component in my test the index.tsx is also rendered leading to issues like that there is no html etc. I have now fixed this issue by warpping the component in the test with its own provider like so:
const {container, findByTestId} = render(() => (
<GlobalContext.Provider value={{oAuthClient: new OAuthClient()}}>
<LogoutButton/>
</GlobalContext.Provider>
));
const {container, findByTestId} = render(() => (
<GlobalContext.Provider value={{oAuthClient: new OAuthClient()}}>
<LogoutButton/>
</GlobalContext.Provider>
));
Is this a correct solution?
2 Replies
aryzing
aryzing14mo ago
You can also use the pattern of separating data acquisition from layout For example, you could have something like the following,
function MyComponentData() {
const data = useGlobalProvider();
const id = useParams().id
// and whatever other data the component needs

return <MyComponent data={data} id={id} />
}
function MyComponentData() {
const data = useGlobalProvider();
const id = useParams().id
// and whatever other data the component needs

return <MyComponent data={data} id={id} />
}
and tests can use MyComponent with whatever mocked data you need
driechel
driechelOP14mo ago
Thanks for your answer. But doesn't this do away with the concecpt of the context provider? The idea behind it is to avoid having to pass certain data through to all children.
Want results from more Discord servers?
Add your server