简体   繁体   中英

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.

I have found through trial and error that renderIntoDocument doesn't work as its a stateless component.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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