如何使用 sinon 监视特定按钮单击的功能?

How to spy on function from specific button click using sinon?

我正在测试我的第一个 React 应用程序,我遇到了两个问题。问题一,当我寻找一个按钮来模拟点击时,我得到了 id='callA' 的按钮,但没有得到具有不同 id 的按钮。我的第二个问题是我正在尝试使用 sinon 来监视带有 id="callA" 调用的 A() 按钮。

我的 React 应用程序

class ReactPage extends React.Component {
  constructor(props) {
      super(props)
      this.B = this.B.bind(this)
      this.C = this.C.bind(this)
  }

  //other functions

  A = () => {
    //stuff that I don't want to run on button click
  }

  render(){
    return(
      <button id="callA" type="submit" onClick={this.A}>Submit</button>
      <button id="callB" type="submit" onClick={(e) => this.B(e.target.value)} value={7}>Call B</button>
      <button id="callC" type="submit" onClick={(e) => this.C(e.target.value)} value={1}>Call C</button>
      <button id="callD" type="submit" onClick={(e) => this.D(e.target.value)} value={2}>Call D</button>
    );
  }
}

这是我尝试对调用 A() 的按钮进行测试

import {shallow, mount, configure} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import sinon from 'sinon';
import ReactPage from './App';

configure({ adapter: new Adapter() });

it('submit button call A()', () => {
  const spy = sinon.spy(ReactPage.prototype, "A");
  const rendered = shallow(<ReactPage />);
  rendered.find("#callA").simulate('click');
  expect(spy.calledOnce).toEqual(true);
});

您可以使用 jest 来监视您的 ReactPage 实例。

it('submit button call A()', () => {
  const rendered = shallow(<ReactPage />);
  const spyOn = jest.spy(rendered.instance(), "A");
  rendered.find("#callA").simulate('click');
  expect(spyOn).toHaveBeenCalled();
});