如何用玩笑和酶模拟React组件事件

时间:2018-07-08 10:29:50

标签: reactjs jestjs enzyme

我已经阅读了关于类似问题的多个SO答案,但是看不到为什么事情对我不起作用。 我已经尝试过this,它确实可以按照已接受的答案中的说明工作,但不适用于模拟事件。

这是组件:

import React, { Component } from 'react';

export default class App extends Component {
  render() {
    return (
      <div>
        <button
          onClick={this.handleClick}>
          Click me
        </button>
      </div>
    );
  }

  func1() {
    console.log("In func1");
    this.func2();
  }

  func2() {
    console.log("In func2");
  }

  handleClick() {
    console.log("handleClick");
  }
}

,以下是测试文件。 test1和test2通过,测试3和test4失败。

import React from 'react';
import { shallow } from 'enzyme';
import App from 'components/App';

const handleClickSpy = jest.spyOn(App.prototype, 'handleClick');
const handleClickMock = jest.fn();

it('test 1 - call handleClick spy', () => {
  let wrapper = shallow(<App/>);
  wrapper.find('button').simulate('click');
  expect(handleClickSpy).toBeCalled();
});

it('test 2 - call func2 mock', () => {
  let wrapper = shallow(<App/>);
  const func2Mock = jest.fn();
  wrapper.instance().func2 = func2Mock;
  // wrapper.update();
  wrapper.instance().func1();
  expect(func2Mock).toBeCalled();
});

it('test 3 - call handleClick mock - take 1', () => {
  let wrapper = shallow(<App/>);
  wrapper.find('button').simulate('click');
  expect(handleClickMock).toBeCalled();
});

it('test 4 - call handleClick mock - take 2', () => {
  let wrapper = shallow(<App/>);
  const handleClickMock2 = jest.fn();
  wrapper.instance().handleClick = handleClickMock2;
  wrapper.update();
  wrapper.find('button').simulate('click');
  expect(handleClickMock2).toBeCalled();
});

console.log的打印输出如下(这意味着在test3和test4中,这两个模拟都无效):

  console.log src\components\App.js:25
    handleClick

  console.log src\components\App.js:16
    In func1

  console.log src\components\App.js:25
    handleClick

  console.log src\components\App.js:25
    handleClick

1 个答案:

答案 0 :(得分:0)

我在airbnb/enzyme #1081

中找到了答案

这两个作品:

it('test 5 - call handleClick mock - take 3', () => {
  App.prototype.handleClick = jest.fn();
  let wrapper = shallow(<App/>);
  let { handleClick } = wrapper.instance();
  wrapper.find('button').simulate('click');
  expect(handleClick).toBeCalled();
});

it('test 6 - call handleClick mock - take 4', () => {
  App.prototype.handleClick = jest.fn();
  let wrapper = shallow(<App/>);
  let { handleClick } = wrapper.instance();
  wrapper.find('button').prop('onClick')();
  expect(handleClick).toBeCalled();
});