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 :*/}
}
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 :*/}
}
Share
Improve this question
edited Nov 8, 2018 at 20:00
skyboyer
23.7k7 gold badges61 silver badges71 bronze badges
asked Jul 12, 2018 at 2:26
SatheshSathesh
4963 gold badges13 silver badges32 bronze badges
1
|
1 Answer
Reset to default 13you 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();
});
simulate()
which is part of the Enzyme API. Under the hood, it is actually just calling theonClick
prop directly (see docs). So if you simulate the click on the button anddeleteData
gets called, you can be sure that the method specified by the onClick was called. – Daniel Bank Commented Jul 12, 2018 at 3:53