我将我的按钮放在一个组件内,该组件在单击时会调用deleteData方法。 我如何测试在按一下按钮时是否调用deleteData方法?
<Modal.Footer>
<Button id="trashBtn" onClick={this.deleteData}>Delete</Button>
<Modal.Footer>
deleteData() {
{/* TODO :*/}
}
答案 0 :(得分:5)
您可以这样做:
我想您的按钮在某个组件中,并且使用该组件的名称作为ComponentName
import React from 'react';
import { shallow } from 'enzyme';
import ComponentName from './ComponentName'
describe('Test Button component', () => {
it('Test click event', () => {
const component = shallow((<ComponentName />));
button.find('button').simulate('click');
//write an expectation here if suppose you are setting state in your deleteData function you can do like this
component.update();//if you are setting state
expect(component.state().stateVariableName).toEqual(value you are expecting after setState in deleteData);
});
});
编辑:对于普通的函数调用测试,我们可以使用spyOn:
it('Test click event', () => {
const FakeFun = jest.spyOn(ComponentName.prototype, 'deleteData');
const component = shallow((<ComponentName />));
button.find('button').simulate('click');
component.update();
expect(FakeFun).toHaveBeenCalled();
});