Dav*_*dia 5 testing reactjs jestjs
我正在使用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();
});
Run Code Online (Sandbox Code Playgroud)
这样的事情存在吗?
我知道这是一个老问题,但如果您仍然需要答案,您应该使用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();
});
Run Code Online (Sandbox Code Playgroud)
And*_*rle -1
问题是find返回一个数组,所以你必须使用first来获取第一个元素或closest:
inst.find('.increment').first().click()
inst.closest('.increment').click()
Run Code Online (Sandbox Code Playgroud)
如果您不想使用第一个元素childAt(index)
| 归档时间: |
|
| 查看次数: |
1930 次 |
| 最近记录: |