Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a function is called in react jest?

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 :*/}
  }
like image 718
Sathesh Balakrishnan Manohar Avatar asked Jul 12 '18 02:07

Sathesh Balakrishnan Manohar


1 Answers

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();
  });
like image 188
aravind_reddy Avatar answered Oct 17 '22 11:10

aravind_reddy