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?
I know this is an old question, but in case you still need the answer, you should use
component.root
(instead ofcomponent.getInstance()
), which has afind()
method on it. However, this differs from enzyme'sfind()
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:The problem is that
find
returns an array, so you have to usefirst
to get the first element orclosest
:If you don't want the first element use
childAt(index)