How to test a function is called in react jest?

梦想与她 提交于 2020-01-14 10:46:28

问题


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 :*/}
  }

回答1:


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


来源:https://stackoverflow.com/questions/51296502/how-to-test-a-function-is-called-in-react-jest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!