简体   繁体   English

在Jest和Sinon无法正常工作的情况下进行测试功能调用

[英]React testing function calls with Jest and Sinon not working

I'm trying to assert the number of times my React class method is called after an event. 我试图断言事件后我的React类方法被调用的次数。 I have tried using sinon.spy and jest.fn() to no avail. 我尝试使用sinon.spy和jest.fn()无济于事。

Using sinon.spy: 使用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);
    });

with jest.fn(): 与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);
    });

I have assurance the method in question is definitely being called. 我敢肯定,有问题的方法一定会被调用。 What is more confusing is a console.log statement in the method prints before the 更令人困惑的是方法中的console.log语句在

console.log(spy.callCount) console.log(spy.callCount)

Any pointers in the right direction will be highly appreciated! 任何正确方向的指针将不胜感激! Cheers! 干杯!

The solution was simple, 解决方案很简单,

I moved the line 我搬了线

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

above the previous line: 在上一行上方:

formInputButton.simulate('click'); formInputButton.simulate('click');

Not sure why this worked, and it would be great to hear from someone as to why this affected the result? 不确定为什么这样做有效,并且很高兴听到某人的消息,为什么这会影响结果?

NOTE: formInputButton doesnt call the function in question 注意:formInputButton不会调用有问题的函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM