本文介绍了如何与ReactTestRenderer/Jest渲染的组件交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working with Jest and snapshot testing. What I'd like to do is render a component with ReactTestRenderer, then simulate clicking a button inside it, then verify the snapshot.

ReactTestRenderer的create调用返回的对象具有getInstance函数,该函数允许我直接调用其方法,但似乎无法与ReactTestUtils中的任何find/scry方法一起使用.

The object returned by ReactTestRenderer's create call has a getInstance function that allows me to call its methods directly, but it does not seem to work with any of the find/scry methods in ReactTestUtils.

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

I can manually traverse the tree and click the button, but it seems like there must be a better way:

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

是否存在类似的东西?

推荐答案

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

I know this is an old question, but in case you still need the answer, you should use component.root (instead of component.getInstance()), which has a find() method on it. However, this differs from enzyme's find() in that it doesn't accept a selector, instead it accepts a function, that gets the element as argument. So it would look something like this:

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

这篇关于如何与ReactTestRenderer/Jest渲染的组件交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 17:33