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

问题描述 投票:-1回答:1

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

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

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

javascript reactjs jestjs enzyme
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.