子组件onClick功能的测试用例

时间:2020-08-29 17:55:50

标签: testing jestjs enzyme chai sinon

我想测试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);
});

1 个答案:

答案 0 :(得分:0)

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来完成。