mardi 16 janvier 2018

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. I have tried using sinon.spy and jest.fn() to no avail.

Using 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():

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(spy.callCount)

Any pointers in the right direction will be highly appreciated! Cheers!

Aucun commentaire:

Enregistrer un commentaire