[英]How to mock a react component's event when fat arrow function is used as event handler?
i want to mock handleClick event of my TodoForm component. 我想模拟TodoForm组件的handleClick事件。
TodoForm.jsx 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>
)
}
}
in TodoForm.test.js 在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();
})
the test fails with "Expected mock function to have been called, but it was not called." 测试失败,并显示“已调用预期的模拟函数,但未调用。”
instead of calling the mock function it calls the real implementation. 而不是调用模拟函数,而是调用真正的实现。
I am using create-react-app, 我正在使用create-react-app,
react:16.6.3, enzyme: 3.8.0, 反应:16.6.3,酶:3.8.0,
enzyme-adapter-react-16 :1.7.1 酶适配器反应16:1.7.1
This is a known issue with Enzyme . 这是酶的一个已知问题 。
update()
doesn't cause a re-render. update()
不会导致重新渲染。 This results in triggering original handleClick
, because render
function was called before mocking the method. 这导致触发原始的
handleClick
,因为在模拟该方法之前调用了render
函数。
A workaround is to use wrapper.instance().forceUpdate()
instead of wrapper.update()
. 一种解决方法是使用
wrapper.instance().forceUpdate()
而不是wrapper.update()
。
Testability is one of several reasons to prefer bound prototype methods over arrow instance methods. 可测试性是与箭头实例方法相比更喜欢绑定原型方法的几个原因之一 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.