gpt4 book ai didi

javascript - 如何检查 onclick 函数是否被触发?

转载 作者:行者123 更新时间:2023-11-30 20:36:10 27 4
gpt4 key购买 nike

你能告诉我如何检查 onclick 函数是否被触发了吗?我的演示中有一个按钮 INCREMENT onclick of button 我想检查是否调用了 onClickHandler 函数

这是我的代码 https://codesandbox.io/s/oq7kwzrnj5

it("check counter increment function is callled", () => {
const wrapper = shallow(<Counter />);
wrapper.find("button").simulate("click");
});

最佳答案

你可以使用像 sinon 这样的库来监视你的类函数:

import sinon from 'sinon';
const sandbox = sinon.createSandbox();

然后,当您设置测试时,在浅渲染您的组件之前:

it("check counter increment function is called", () => {
const spy = sandbox.spy(Counter.prototype, 'onClickHandler');
const wrapper = shallow(<Counter />);
wrapper.find("button").simulate("click");
expect(spy.called).toBe(true);
});

更新:

onClickHandler 不应定义为匿名函数,而应使用:

onClickHandler() {
const incrementCounter = this.state.counter + 1;
this.setState({
counter: incrementCounter
});
}

在你的渲染函数中,绑定(bind)这个:

render() {
return (
<div>
<p>{this.state.counter}</p>
<button onClick{this.onClickHandler.bind(this)}>INCREMENT</button>
</div>
);
}

使用 Jest 更新

其实,你甚至不需要像sinon这样的第三方库。您可以使用 Jest 实现相同的目的:

it("check counter increment function is called", () => {
const spy = jest.spyOn(Counter.prototype, "onClickHandler");
const wrapper = shallow(<Counter />);
wrapper.find("button").simulate("click");
expect(spy).toBeCalled();
});

关于javascript - 如何检查 onclick 函数是否被触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49815076/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com