Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enzyme test nested component's method

Tags:

reactjs

enzyme

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 ?

like image 753
Théo Champion Avatar asked Jun 08 '18 17:06

Théo Champion


2 Answers

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();
like image 170
Shishir Anshuman Avatar answered Nov 12 '22 09:11

Shishir Anshuman


Try to find(ApolloProvider).dive() - and console.log it to see the tree inside.

like image 21
Palaniichuk Dmytro Avatar answered Nov 12 '22 10:11

Palaniichuk Dmytro