测试React组件时未调用Jest模拟

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

[我正在尝试编写一个使用酶来模拟按钮点击的测试,该测试期望触发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();
    });
reactjs unit-testing mocking jestjs enzyme
1个回答
0
投票

原因是当浅层渲染Form组件时,原始的onHandleSubmit方法已经绑定到onClick。因此,即使您将onHandleSubmitMock分配给Form组件的实例。晚了”。模拟click事件时,它将触发原始的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
© www.soinside.com 2019 - 2024. All rights reserved.