【问题标题】:React testing function calls with Jest and Sinon not working使用 Jest 和 Sinon 的反应测试函数调用不起作用
【发布时间】:2018-01-16 17:04:57
【问题描述】:

我试图断言我的 React 类方法在事件之后被调用的次数。我尝试使用 sinon.spy 和 jest.fn() 无济于事。

使用 sinon.spy:

test('Some test', (done) => {
  const page = renderLookupPage();
  const formInputButton = page.find('.button').first();
  formInputButton.simulate('click');

  let spy = sinon.spy(page.instance().myReactMethod);

  const button = page.find('.tag').first();
  button.simulate('click');

  setTimeout(() => {
        try {
            console.log(spy.callCount); //0
          done();
        } catch (error) {
          done.fail(error);
        }
      }, 100);
    });

用 jest.fn():

test('Some test', (done) => {
  const page = renderLookupPage();
  const formInputButton = page.find('.button').first();
  formInputButton.simulate('click');

  page.instance().myReactMethod = jest.fn(() => {});

  const button = page.find('.tag').first();
  button.simulate('click');

      setTimeout(() => {
        try {
            console.log(page.instance().myReactMethod.mock.calls.length); //0
          done();
        } catch (error) {
          done.fail(error);
        }
      }, 100);
    });

我保证肯定会调用相关方法。更令人困惑的是方法中的 console.log 语句在

之前打印

console.log(spy.callCount)

任何指向正确方向的指针都将受到高度赞赏!干杯!

【问题讨论】:

    标签: javascript reactjs testing sinon jestjs


    【解决方案1】:

    解决方法很简单,

    我移动了这条线

    page.instance().myReactMethod = jest.fn(() => {});

    上一行:

    formInputButton.simulate('click');

    不知道为什么会这样,很高兴听到有人说为什么这会影响结果?

    注意:formInputButton 不会调用相关函数

    【讨论】:

      猜你喜欢
      • 2020-06-02
      • 2019-07-27
      • 2021-05-20
      • 2017-09-14
      • 2020-08-22
      • 2021-04-26
      • 1970-01-01
      • 1970-01-01
      • 2016-08-03
      相关资源
      最近更新 更多