我正在使用 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();
});
这样的事情存在吗?
我知道这是一个老问题,但如果您仍然需要答案,您应该使用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();
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)