我有一个按钮在组件内,当点击该按钮时会调用deleteData方法。如何使用Jest测试按钮点击是否调用了deleteData方法?
<Modal.Footer>
<Button id="trashBtn" onClick={this.deleteData}>Delete</Button>
<Modal.Footer>
deleteData() {
{/* TODO :*/}
}
我有一个按钮在组件内,当点击该按钮时会调用deleteData方法。如何使用Jest测试按钮点击是否调用了deleteData方法?
<Modal.Footer>
<Button id="trashBtn" onClick={this.deleteData}>Delete</Button>
<Modal.Footer>
deleteData() {
{/* TODO :*/}
}
你可以像这样做:
我假设你的按钮在某个组件中,我将使用该组件的名称作为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 />));
component.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('calls click event', () => {
const FakeFun = jest.spyOn(ComponentName.prototype, 'deleteData');
const component = shallow((<ComponentName />));
component.find('button').simulate('click');
component.update();
expect(FakeFun).toHaveBeenCalled();
});
simulate()
。实际上,在幕后它只是直接调用onClick
属性(请参见文档)。所以,如果你模拟点击按钮并且调用了deleteData
,那么你可以确定onClick
指定的方法已经被调用。 - Daniel Bank