I'm using React's Context API to pass some context to lower level components.
I want to be able to run the component without a context provider (for testing). For this to work, I need to check whether there is a context provider around my component.
Example code:
const Wrapper = () => {
// in my real app, there are some levels
// between the provider and the child component
return <NameProvider value={name: 'User'}>
<ChildComponent />
</NameProvider>
}
const ChildComponent = () => {
if (/* what can I put here ? */) {
// inside Provider
return <NameConsumer>
{context => <span>{context.name}</span>}
</NameConsumer>
} else {
// no provider available, e.g. in a test file
return <span>Test Text</span>
}
}
This question is not specifically about testing. There could be other situations where a component needs to work both inside and outside a context provider.
Providerin the place where you defineChildComponent, especially if this is for testing purposes.