Javascript 如何在react中检查onclick函数是否被激发?

Javascript 如何在react中检查onclick函数是否被激发?,javascript,reactjs,unit-testing,react-redux,enzyme,Javascript,Reactjs,Unit Testing,React Redux,Enzyme,您能告诉我如何在react中检查onclick函数是否启动吗? 我在我的演示中有一个按钮INCREMENTonclick我想检查的按钮是否调用了onClickHandler函数 这是我的密码 it(“调用了检查计数器增量函数”,()=>{ 常量包装器=浅(); 包装器。查找(“按钮”)。模拟(“单击”); }); 您可以使用类似sinon的库来监视您的类函数: import sinon from 'sinon'; const sandbox = sinon.createSandbox();

您能告诉我如何在react中检查onclick函数是否启动吗? 我在我的演示中有一个按钮
INCREMENT
onclick我想检查的按钮是否调用了
onClickHandler
函数

这是我的密码

it(“调用了检查计数器增量函数”,()=>{
常量包装器=浅();
包装器。查找(“按钮”)。模拟(“单击”);
});

您可以使用类似sinon的库来监视您的类函数:

import sinon from 'sinon';
const sandbox = sinon.createSandbox();
然后,在设置测试时,在渲染组件之前:

it("check counter increment function is callled", () => {
  const spy = sandbox.spy(Counter.prototype, 'onClickHandler');
  const wrapper = shallow(<Counter />);
  wrapper.find("button").simulate("click");
  expect(spy.called).toBe(true);
});
在渲染函数中,绑定以下内容:

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

增量 ); }
使用Jest更新

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

it("check counter increment function is callled", () => {
  const spy = jest.spyOn(Counter.prototype, "onClickHandler");
  const wrapper = shallow(<Counter />);
  wrapper.find("button").simulate("click");
  expect(spy).toBeCalled();
});
it(“调用了检查计数器增量函数”,()=>{
constspy=jest.spyOn(Counter.prototype,“onClickHandler”);
常量包装器=浅();
包装器。查找(“按钮”)。模拟(“单击”);
expect(spy.toBeCalled();
});
在onClick中添加
console.log()

it("check counter increment function is callled", () => {
    console.log('Im here')
    const wrapper = shallow(<Counter />);
    wrapper.find("button").simulate("click");
 });
it(“调用了检查计数器增量函数”,()=>{
console.log('Im here')
常量包装器=浅();
包装器。查找(“按钮”)。模拟(“单击”);
});

我将控制台日志添加到您的代码中,它工作正常

     onClickHandler = () => {
         console.log("Hello");
          const increamentCounter = this.state.counter + 1;
            this.setState({
            counter: increamentCounter
          });
       };

所以onClickHandler工作正常。对于失败的测试,我认为这可能会有所帮助

您是否尝试使用console.log?对我不起作用onclick正在运行finetest case man,,,我需要检查test caseConsole.log在编写自动测试时并没有真正解决任何问题。这是因为onclick处理程序被定义为匿名函数(胖箭头函数)。试试下面的方法,它就工作了:onClickHandler(){const incrementCounter=this.state.counter+1;this.setState({counter:incrementCounter});}不是吗
expect(spy).tohavebeencall()开玩笑?不同的匹配器-效果相同;)只是语法上的糖分。当您试图在自动化测试中实现这一点时,这并没有真正的帮助。console.logging在编写自动化测试时并不真正有用
it("check counter increment function is callled", () => {
    console.log('Im here')
    const wrapper = shallow(<Counter />);
    wrapper.find("button").simulate("click");
 });
     onClickHandler = () => {
         console.log("Hello");
          const increamentCounter = this.state.counter + 1;
            this.setState({
            counter: increamentCounter
          });
       };