使用Jest / Enzyme进行按钮单击的方法调用的间谍

时间:2019-12-25 18:45:07

标签: javascript reactjs jestjs enzyme

我要测试的方法在单击按钮时被调用。我有以下代码:

import React from 'react';

export default class Btn extends React.Component {
  constructor(props) {
    super(props);
    this.toggleClick = this.toggleClick.bind(this);
  }


  toggleClick() {
    const { onClick } = this.props;
    onClick();
  }

  render() {

    return (
      <button
        className="btn"
        onClick={this.toggleClick}
      >
        <div />
      </button>
    );
  }
}

我编写了这样的测试来测试onToggleClick是否被调用:

test('test button click', () => {
   const wrapper = shallow(<Btn {...props} />);

    const instance = wrapper.instance();
    const spyOnClick = jest.spyOn(instance, 'toggleClick');

    wrapper.find('button').simulate('click');

    expect(spyOnClick).toHaveBeenCalled();
  });

但是控制台输出中的内容是

Expected number of calls: >= 1
Received number of calls:    0

我不知道我的错误在哪里或我做错了什么。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

在浅呈现组件之前,您需要使用jest.spyOn

例如

index.jsx

import React from 'react';

export default class Btn extends React.Component {
  constructor(props) {
    super(props);
    this.toggleClick = this.toggleClick.bind(this);
  }

  toggleClick() {
    const { onClick } = this.props;
    onClick();
  }

  render() {
    return (
      <button className="btn" onClick={this.toggleClick}>
        <div />
      </button>
    );
  }
}

index.spec.jsx

import { shallow } from 'enzyme';
import Btn from './';

describe('59481051', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });
  test('test button click', () => {
    const props = { onClick: jest.fn() };
    const spyOnClick = jest.spyOn(Btn.prototype, 'toggleClick');
    const wrapper = shallow(<Btn {...props} />);
    wrapper.find('button').simulate('click');
    expect(spyOnClick).toHaveBeenCalled();
    expect(props.onClick).toHaveBeenCalled();
  });
});

覆盖率100%的单元测试结果:

PASS  src/stackoverflow/59481051/index.spec.jsx (12.053s)
  59481051
    ✓ test button click (15ms)

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |      100 |      100 |      100 |      100 |                   |
 index.jsx |      100 |      100 |      100 |      100 |                   |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        13.703s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59481051