子组件onClick函数的测试用例

Test case for child components onClick function

我想测试 MenuPopover.Item id={3} 的 onClick 功能,点击后是否被调用一次。

import React from 'react';
import copy from 'copy-to-clipboard';

const TableMenu = ({show, target, onClick, onHide, addedType, disable, readonly, rowId, supportRestore, supportDelete, isRestored}) => (
    <MenuPopover
        onClick={onClick}
        onHide={onHide}>
        {!readonly && (addedType ?
            <MenuPopover.Item id={1} label='Delete' disabled=true/> :
            <MenuPopover.Item id={2} label='Restore' disabled=false/>
        )}
        <MenuPopover.Item id={3} onClick={() => copy(rowId)} label='Copy'/>
    </MenuPopover>
);

到目前为止编写的测试用例

const onCopySpy = sinon.spy();
const props = {
    ///
    onCopy: onCopySpy,
    ///
};

it('check method onCopy called', () => {
    const wrapper = shallow(<TableMenu {...props}/>);
    expect(wrapper.find('MenuPopover').children()).to.have.lengthOf(2);
    wrapper.find(MenuPopover.Item).... //Test case to call the onClick function
    expect(onCopySpy.calledOnce).to.eql(true);
});

copy 需要在测试中模拟:

import copy from 'copy-to-clipboard';
jest.mock('copy-to-clipboard', () => sinon.spy());

...

const wrapper = shallow(<TableMenu {...props}/>);
wrapper.find(MenuPopover.Item).props().onClick();
expect(copy.calledOnce).to.eql(true);

这也可以用 simulate 来完成,但 does the same thing internally.