How to interact with components rendered by ReactTestRenderer / Jest

拥有回忆 提交于 2020-01-02 04:48:29

问题


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.

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

Does something like this exist?


回答1:


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



回答2:


The problem is that find returns an array, so you have to use first to get the first element or closest:

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

If you don't want the first element use childAt(index)



来源:https://stackoverflow.com/questions/40688661/how-to-interact-with-components-rendered-by-reacttestrenderer-jest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!