【问题标题】:How to interact with components rendered by ReactTestRenderer / Jest如何与 ReactTestRenderer / Jest 渲染的组件交互
【发布时间】:2017-04-02 23:42:59
【问题描述】:

我正在使用 Jest 和快照测试。我想做的是用ReactTestRenderer 渲染一个组件,然后模拟单击其中的一个按钮,然后验证快照。

ReactTestRenderer 的 create 调用返回的对象有一个 getInstance 函数,允许我直接调用它的方法,但它似乎不适用于 ReactTestUtils 中的任何 find/scry 方法。

我可以手动遍历树并点击按钮,但似乎必须有更好的方法:

import React from 'react';
import ReactDOM from 'react-dom';
import MyCounter from './MyCounter';
import renderer from 'react-test-renderer';
import {Simulate, findRenderedDOMComponentWithClass} from 'react-addons-test-utils';

it('should render 0', () => {
  const component = renderer.create(<MyCounter/>);
  const inst = component.getInstance();

  // Calling methods directly works, but that's not the same as
  // simulating a click on the button...
  inst.increment();

  // This also works, but it's awfully verbose...
  component.toJSON().children[1].props.onClick();

  // I'm looking for something like...
  //   inst.find('.increment').click()
  // or:
  //   Simulate.click(inst.find('.increment'))
  // or:
  //   Simulate.click(findRenderedDOMComponentWithClass(inst, 'increment'))

  // Finally, verify the snapshot
  expect(component.toJSON()).toMatchSnapshot();
});

这样的东西存在吗?

【问题讨论】:

  • 您正在寻找的是 Enzyme:airbnb.io/enzyme ...但是 jest 确实需要一个横向快照的工具,因为 Enzyme 引入了更多不必要的东西和潜在的瓶颈。我认为 2017 年的目标只是使用 Jest。当 React 如此可靠时,实际上并不需要模拟点击(通过 DOM)。此外,当快照结合无状态组件如此强大时,您几乎不需要 css 样式选择器。这样就只剩下需要选择器来快速调用用作道具的函数了。现在必须有一个具有基本选择器的库..

标签: reactjs testing jestjs


【解决方案1】:

我知道这是一个老问题,但如果你仍然需要答案,你应该使用component.root(而不是component.getInstance()),它上面有一个find() 方法。但是,这与酶的find() 不同,因为它不接受选择器,而是接受一个函数,该函数将元素作为参数。所以它看起来像这样:

it('should render 0', () => {
  const component = renderer.create(<MyCounter/>);
  const root = component.root;

  const incrementButton = root.find(element => element.props.className === 'increment');
  incrementButton.props.onClick();

  expect(component.toJSON()).toMatchSnapshot();
});

【讨论】:

    【解决方案2】:

    问题是find返回一个数组,所以你必须使用first来获取第一个元素或者closest

    inst.find('.increment').first().click()
    inst.closest('.increment').click()
    

    如果您不想要第一个元素,请使用childAt(index)

    【讨论】:

    • inst 上没有 find 方法
    • 啊抱歉,我以为你在用酶。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    • 2019-12-27
    • 2018-05-21
    相关资源
    最近更新 更多