如何测试在react玩笑中调用的函数?

IT技术 javascript reactjs jestjs enzyme
2021-05-10 16:31:38

我在一个组件中有我的按钮,它在单击时调用方法 deleteData。如何测试在玩笑中单击按钮时调用的 deleteData 方法?

<Modal.Footer>
  <Button id="trashBtn" onClick={this.deleteData}>Delete</Button>
<Modal.Footer>

deleteData() {
    {/* TODO :*/}
  }
1个回答

你可以这样做:

我想你的按钮在某个组件中,我使用该组件的名称作为 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);  
  });
});

编辑:对于函数调用的简单测试,我们可以使用 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();
  });