I have my button inside a component, which calls a method deleteData on click. How do I test the deleteData method is called on the button click in jest?
<Modal.Footer>
<Button id="trashBtn" onClick={this.deleteData}>Delete</Button>
<Modal.Footer>
deleteData() {
{/* TODO :*/}
}
you can do it like this:
I suppose your button is in some component and iam using that component's name as 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);
});
});
Edit: for plain test of function call we can use 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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With