问题
I'm trying to use Enzyme to test a component's method. I know the typical way to do this is to use Enzyme's instance()
method.
The thing is, this only work for root
component and my component need to be wrapper in two Context provider to render (namely, react-router and apollo client).
const wrapper = mount(
<ApolloProvider client={client}>
<MemoryRouter initialEntries={["/login"]}>
<AuthFormContainer />
</MemoryRouter>
</ApolloProvider>
);
How can I test methodA
of AuthFormContainer
in that case ?
回答1:
For the unit testing, you should not be worried about the other components. But if you must, you may use the shallow rendering. Here is what I did:
const wrapper = shallow(
<ApolloProvider client={client}>
<MemoryRouter initialEntries={["/login"]}>
<AuthFormContainer />
</MemoryRouter>
</ApolloProvider>
);
Get the Component tree for the AuthFormContainer
using:
const authFormControllerTree = wrapper.find(MemoryRouter).shallow().find(AuthFormContainer).shallow()
Now to test the methodA
in the AuthFormContainer
, you may just do:
authFormControllerTree.instance().methodA();
回答2:
Try to find(ApolloProvider).dive()
- and console.log it to see the tree inside.
回答3:
For React components you always write Unit Tests. According to this answer: https://stackoverflow.com/a/652382/2873331:
Unit testing simply verifies that individual units of code (mostly functions) work as expected...
So here you should try to Test functionality of AuthFormContainer
and not whether react-router and apollo client are injecting context correctly or not. Your test case should test: Given the context
to the AuthFormContainer
, do its instance methods work as expected or not.
To inject context you can use Enzyme's shallow method.
it('should work as expected', () => {
const wrapper = shallow(< AuthFormContainer />, {
context: { ... }, // pass expected context here
});
wrapper.instance().method(); //extract the required method by using instance
...
});
Reference: http://airbnb.io/enzyme/docs/api/shallow.html
On a side note, do not use mount
unless you actually want to test things at DOM level. mount
makes your tests very slow. Always prefer shallow
.
Reference: http://airbnb.io/enzyme/docs/api/mount.html
回答4:
Always test wrapper component differently than connected component. Export wrapper component and import to test file and test as you are doing but shallow ( I prefer)
来源:https://stackoverflow.com/questions/50765447/enzyme-test-nested-components-method