How to test a function is called in react jest?

后端 未结 1 979
渐次进展
渐次进展 2021-01-19 00:41

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?

<         


        
相关标签:
1条回答
  • 2021-01-19 01:24

    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 />));
        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);  
      });
    });
    

    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 />));
        button.find('button').simulate('click');
        component.update();
        expect(FakeFun).toHaveBeenCalled();
      });
    
    0 讨论(0)
提交回复
热议问题