我有一个可点击的组件,如下所示:
export default class Clickable extends Component {
constructor(props){
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
console.log('clicked');
}
render(){
return <button onClick={this.handleClick}></button>
}
}
我已在浏览器中确认onClick事件正在触发并调用句柄单击功能。但是,我无法通过模拟点击事件获得我的测试(jest / enzyme)。我的测试看起来如下。
describe("<Clickable/>", () => {
let clickMock = jest.fn();
let component = shallow(<Clickable/>);
it("should call handleClick() when clicked on", () => {
component.instance().handleClick = clickMock;
component.update();
component.find('button').simulate('click');
expect(clickMock).toHaveBeenCalled();
});
});
测试返回Expected mock function to have been called.
由于
答案 0 :(得分:0)
尝试:
import React from "react";
import { shallow } from "enzyme";
import Foo from "path/Foo"
describe("Executes a handler function", () => {
it("must call the mock method with button click", () => {
const wrapper = shallow(<Foo />);
const button = wrapper.find("button");
const instance = wrapper.instance();
instance.btnClick = jest.fn(instance.btnClick);
button.simulate("click");
expect(instance.btnClick).toHaveBeenCalled();
});
});