简体   繁体   English

使用须低渲染测试无状态反应组件中的交互

[英]Testing interactions in stateless react component using shalllow rendering

I have a stateless component which I want to test 我有一个要测试的无状态组件

const PageSizer = ({itemsPerPage, onItemsPerPageChange}) => (
    <form>
       <label>Items Per Page </label>
       <select value={itemsPerPage} onChange={(e) => {onItemsPerPageChange(e.target.value) }}>
           <option value="10">10</option>
           <option value="25">25</option>
           <option value="50">50</option>
           <option value="100">100</option>
       </select>
   </form>)

I want to test that when the select value is change it triggers the onItemsPerPageChange callback with the option value. 我想测试一下,当选择值更改时,它会触发带有选项值的onItemsPerPageChange回调。

I have found through trial and error that renderIntoDocument doesn't work as its a stateless component. 通过反复试验,我发现renderIntoDocument不能作为其无状态组件使用。

Using shallow rendering how would I test this? 使用浅渲染,我将如何测试呢?

I have come up with 我想出了

it('should call onItemsPerPageChange when select value is changed', () => {

    var spy = expect.createSpy();

    var shallowRenderer = TestUtils.createRenderer();
    shallowRenderer.render(<PageSizer onItemsPerPageChange={spy}  />)
    var result = shallowRenderer.getRenderOutput();

    var select = result.props.children[1]
    TestUtils.Simulate.change(select, { target: { value: 25 } });

    expect(spy).toHaveBeenCalledWith(25)
});

The spy is never called though. 间谍从未被召唤。 Am I doing this right? 我这样做对吗?

I managed to get it working by calling the onChange prop directly 我设法通过直接调用onChange道具使其工作

select.props.onChange({ target: { value: 25 } })

as I noticed they did with the click event in https://github.com/facebook/react/blob/master/src/test/ tests /ReactTestUtils-test.js 正如我注意到的,他们对https://github.com/facebook/react/blob/master/src/test/ tests /ReactTestUtils-test.js中的click事件做了处理

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM