酶联测试嵌套组件的方法 [英] Enzyme test nested component's method

查看:53
本文介绍了酶联测试嵌套组件的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用酶来测试组件的方法。我知道执行此操作的典型方法是使用酶的 instance()方法。

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.

问题是,这仅适用于 root 组件,并且我的组件需要包装在两个Context提供程序中以进行渲染(即react-router和apollo客户端)。

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>
  );

如何测试 methodA c $ c> AuthFormContainer 在那种情况下?

How can I test methodA of AuthFormContainer in that case ?

推荐答案

对于单元测试,您不应担心其他组件。但是,如果必须,则可以使用浅渲染。这是我所做的事情:

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>
);

使用以下命令获取 AuthFormContainer 的组件树:

Get the Component tree for the AuthFormContainer using:

const authFormControllerTree = wrapper.find(MemoryRouter).shallow().find(AuthFormContainer).shallow()

现在要测试<$ c $中的方法A c> AuthFormContainer ,您可以这样做:

Now to test the methodA in the AuthFormContainer, you may just do:

authFormControllerTree.instance().methodA();

这篇关于酶联测试嵌套组件的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆