【问题标题】:Jest mock is not being called when testing a react component测试反应组件时未调用 Jest mock
【发布时间】:2020-05-25 02:13:23
【问题描述】:

我正在尝试编写一个使用酶模拟按钮单击的测试,该按钮期望触发 onClick 处理程序。我想用模拟替换组件的 onClick 处理程序。测试运行时,将调用组件类方法而不是模拟函数。任何指导将不胜感激!

下面是测试输出:

  FAIL  src/Form.test.js
  ● Console

    console.log src/Form.js:5
      this is from the component

  ● Submit handler called on click

    expect(jest.fn()).toHaveBeenCalled()

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

      14 |   submitButton.simulate("click");
      15 | 
    > 16 |   expect(onHandleSubmitMock).toHaveBeenCalled();
         |                              ^
      17 | });
      18 | 

      at Object.<anonymous>.test (src/Form.test.js:16:30)

包版本: “笑话”:25.1.0 “开玩笑酶”:7.1.2 “反应”:16.8.6

Form.js 组件


    import React, { Component } from "react";

    export class Form extends Component {
      onHandleSubmit = () => {
        console.log("this is from the component");
      };

      render() {
        return (
          <div>
            <button data-test="submit" onClick={this.onHandleSubmit}>
              Submit
            </button>
          </div>
        );
      }
    }

    export default Form;

Form.test.js


    import React from "react";
    import { shallow } from "enzyme";

    import Form from "./Form";

    test("Submit handler called on click", () => {
      const onHandleSubmitMock = jest.fn(() => console.log("mock was called"));
      const wrapper = shallow(<Form />);

      wrapper.instance().onHandleSubmit = onHandleSubmitMock;
      wrapper.update();

      const submitButton = wrapper.find(`[data-test="submit"]`);
      submitButton.simulate("click");

      expect(onHandleSubmitMock).toHaveBeenCalled();
    });

【问题讨论】:

  • 我强烈建议不要模拟你认为你正在测试的东西的一部分。模拟出合作者(在本例中为console.log)。
  • @jonrsharpe 感谢您的意见。添加了 console.log 是为了弄清楚测试发生了什么。我的意图是测试以确保调用 onHandlerSubmit。那不是合作者吗?
  • 不,它是您正在测试的组件的一部分。您应该通过公共 API 进行测试,基本上是道具和渲染的 DOM,而不是通过内部。测试行为,而不是执行。
  • 谢谢@jonrsharpe!我仍在努力解决所有这些测试问题。这很有帮助。

标签: reactjs unit-testing mocking jestjs enzyme


【解决方案1】:

原因是在浅渲染Form组件时,原来的onHandleSubmit方法已经绑定到onClick。因此,即使您将onHandleSubmitMock 分配给Form 组件的实例。晚了”。当您模拟点击事件时,它会触发原始的onHandleSubmit 方法,而不是模拟的方法。

如果您坚持用模拟的方法替换 onHandleSubmit 方法。 你需要确保在浅渲染之前替换方法(绑定到onClick

例如 form.jsx:

import React from 'react';
import { shallow } from 'enzyme';
import Form from './form';

test('Submit handler called on click', () => {
  const onHandleSubmitMock = jest.fn(() => console.log('mock was called'));
  Form.prototype.onHandleSubmit = onHandleSubmitMock;
  const wrapper = shallow(<Form />);
  const submitButton = wrapper.find(`[data-test="submit"]`);
  submitButton.simulate('click');

  expect(onHandleSubmitMock).toHaveBeenCalled();
});

form.test.jsx:

import React, { Component } from 'react';

export class Form extends Component {
  constructor() {
    this.onHandleSubmit = this.onHandleSubmit.bind(this);
  }
  onHandleSubmit() {
    console.log('this is from the component');
  }

  render() {
    return (
      <div>
        <button data-test="submit" onClick={this.onHandleSubmit}>
          Submit
        </button>
      </div>
    );
  }
}

export default Form;

带有覆盖率报告的单元测试结果:

 PASS  stackoverflow/60138901/form.test.jsx (6.937s)
  ✓ Submit handler called on click (44ms)

  console.log stackoverflow/60138901/form.test.jsx:6
    mock was called

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |   91.67 |      100 |      75 |      90 |                   
 form.jsx |   91.67 |      100 |      75 |      90 | 8                 
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        8.65s

【讨论】:

  • 谢谢!那成功了。我根据@jonrsharpe 的建议更新了我的测试,以测试行为,而不是实现。
猜你喜欢
  • 2018-08-30
  • 2021-08-02
  • 2021-09-24
  • 2020-12-04
  • 1970-01-01
  • 2015-09-10
  • 2020-11-28
  • 2023-03-27
  • 1970-01-01
相关资源
最近更新 更多