Closed craigkovatch closed 2 years ago
The way to test a Provider is to use a component that has the Consumer in it. In other words, List itself has to be using the consumer. What does List look like?
same problem, someone help me please
how to get listPage instance
listPage.js
listPage.test.js
const setup1 = () => {
const initialState = {}
let mockStore = configureStore()
let store = mockStore(initialState)
return (
<Provider store={store}>
<ListPage />
</Provider>
)
}
const setup2 = () => {
return (
<ListPage />
)
}
describe('>>> test', () => {
it('+++ test', () => {
const wrapper1 = shallow(setup1())
console.log(wrapper.debug())
})
})
setup1 debug
setup2 debug
@ljharb that sounds like taking a testing dependency on the implementation details of a consuming component, which seems like a bit of an antipattern to me. I'm additionally confused because IIRC JSX <Context.Provider>
just maps to another layer of React.createElement
. Must be something I'm missing here because my expectation is that a Provider would work like any other component in the React tree.
@craigkovatch i'm not sure what you mean. If you have a component that accepts context, the component has already taken on that dependency, and forced all consumers to know that somewhere in the react tree, they need to inject the Provider. Thus, tests need to do the same.
If you don't want to do that, then don't use React Context, because that's precisely how it works.
Ah, ok. So you’re suggesting I write a mock component to test consuming the context value, rather than testing the provider prop directly.
This works, but still seems more complex to me. I know you’ve put lots of thought into the paradigms here — could you help me understand why you don’t think the provider value should (also?) be directly testable in the way I suggested in my original report?
Either way. It's perfectly fine to test the provider prop directly, because "the provider" is already an implicit dependency of the component.
React simply doesn't provide a way to test Providers directly, outside of the render pipeline (the same is true for hooks, and almost everything else).
Ok, thanks Jordan.
I searched the Issues history and common issues and didn't find anything speaking to this. There's lots of discussion about how to mock a context, but I'm looking for a way to actually test the value of a
Context.Provider
.The render tree of my component looks like this:
JSX transforms context providers into a standard
React.createElement
call, i.e.:Expected behavior
I expected the following test code to work:
Current behavior
The above code does not work; the
ListIsActiveContext.Provider
doesn't appear at all in the enzyme.debug()
tree output.Your environment
API
mount
Version
Adapter
enzyme-adapter-react-16