当胖箭头函数用作事件处理程序时如何模拟反应组件的事件?

How to mock a react component's event when fat arrow function is used as event handler?

我想模拟我的 TodoForm 组件的 handleClick 事件。

TodoForm.jsx

import React, { Component } from "react";

    export class TodoForm extends Component {

        handleClick = () => {
            console.log("handle click is called");
        }

        render() {
            return (
                <div>
                    <button onClick={this.handleClick}>Clik</button>
                </div>
            )
        }
    }

在TodoForm.test.js

import React from 'react'
import { mount, shallow } from 'enzyme'
import { TodoForm } from "../TodoForm";


it("must call the mock function when button is clicked", () => {
    const mocked = jest.fn();
    const wrapper = mount(<TodoForm />);

    wrapper.instance().handleClick = mocked;
    wrapper.update();

    wrapper.find("button").simulate("click");
    expect(mocked).toHaveBeenCalled();


})

测试失败 "Expected mock function to have been called, but it was not called."

它调用真正的实现而不是调用模拟函数。

我正在使用 创建反应应用程序,

反应:16.6.3, 酶:3.8.0,
酶适配器反应 16 :1.7.1

这是一个known issue with Enzymeupdate() 不会导致重新渲染。这导致触发原始 handleClick,因为 render 函数在模拟方法之前被调用。

解决方法是使用 wrapper.instance().forceUpdate() 而不是 wrapper.update()

可测试性 优先使用绑定原型方法而不是箭头实例方法。