子组件onClick功能的测试用例

问题描述

我想测试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来完成。