最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to test a function is called in react jest? - Stack Overflow

programmeradmin1浏览0评论

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 Per the answer by @aravind_reddy, use simulate() which is part of the Enzyme API. Under the hood, it is actually just calling the onClick prop directly (see docs). So if you simulate the click on the button and deleteData gets called, you can be sure that the method specified by the onClick was called. – Daniel Bank Commented Jul 12, 2018 at 3:53
Add a comment  | 

1 Answer 1

Reset to default 13

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();
  });
发布评论

评论列表(0)

  1. 暂无评论