问题描述
我想模拟我的TodoForm组件的handleClick事件.
i want to mock handleClick event of my TodoForm component.
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>
)
}
}
在TodoForm.test.js中
in 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.
我正在使用create-react-app,
I am usingcreate-react-app,
反应:16.6.3, 酶:3.8.0,
酶适配器反应16:1.7.1
react:16.6.3, enzyme: 3.8.0,
enzyme-adapter-react-16 :1.7.1
推荐答案
这是已知问题酶. update()
不会导致重新渲染.导致触发原始handleClick
,因为在模拟该方法之前调用了render
函数.
This is a known issue with Enzyme. update()
doesn't cause a re-render. This results in triggering original handleClick
, because render
function was called before mocking the method.
一种解决方法是使用wrapper.instance().forceUpdate()
代替wrapper.update()
.
A workaround is to use wrapper.instance().forceUpdate()
instead of wrapper.update()
.
可测试性是出于多种原因之一倾向于使用绑定原型方法而不是箭头实例方法.
Testability is one of several reasons to prefer bound prototype methods over arrow instance methods.
这篇关于当使用胖箭头功能作为事件处理程序时,如何模拟React组件的事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!