【问题标题】:Unit test - Link in React using Jest & Enzyme单元测试 - 使用 Jest 和 Enzyme 链接 React
【发布时间】:2019-05-06 11:50:01
【问题描述】:

我在组件中有链接。我在 app.js 中指定了路由路径。

当我尝试使用 Swallow 和 Mount 在组件内查找 Link 控件时,它会抛出错误。

任何人都可以分享示例以在组件内查找链接按钮 代码

 it('includes link to Next Exam', () => {
        const home = shallow(
          <StaticRouter>
            <ComponentForm/>
          </StaticRouter>,
        );
        expect(home.find(Link)).toHaveLength(1);
      });

【问题讨论】:

  • 请分享您尝试使用的代码,我们可以帮助您了解其中的问题。
  • @MatthewHerbst 更新了代码
  • LinkComponentForm 还是StaticRouter 中?
  • @MatthewHerbst 它在 ComponentForm 中。我放置的静态路由器是因为我在运行测试时遇到了一些错误。

标签: reactjs react-redux jestjs enzyme babel-jest


【解决方案1】:

Enzyme shallow 特别意味着不能测试正在通过的组件的子组件。因为StaticRouter 是父组件,ComponentForm 永远不会被正确渲染,所以Link 永远不会出现在视图中。因此,使用shallow,您可以测试StaticRouter 是否正确呈现ComponentForm,但您无法查看ComponentForm 内部。

你有两个选择:

首先,您可以将ComponentForm 传递给shallow 方法。您在 cmets 中提到这导致事情破裂。这可能是因为ComponentForm 期望来自StaticRouter 的道具。您可以手动传递这些:

shallow(<ComponentForm routerProp1={'foo'} routerProp2={'bar'} />);

您的另一个选择是使用Enzyme render 进行深度渲染。只需将 shallow 替换为 render 即可。请注意,不鼓励这样做有几个原因。首先,如shallow 所述,通过不进行shallow 渲染,您可能允许自己测试您传入的组件不知道的内容。例如,StaticRouter 不知道ComponentFormLink,因此ComponentFormLink 的测试应该独立于StaticRouter。其次,rendershallow 慢得多,所以如果您有大量测试和大量组件,您会发现速度相当慢。

【讨论】:

    猜你喜欢
    • 2018-12-16
    • 1970-01-01
    • 2017-11-26
    • 2020-08-27
    • 2017-11-10
    • 2020-11-20
    • 2020-08-07
    • 2019-01-27
    • 2019-08-01
    相关资源
    最近更新 更多