Aristarhys
Aristarhys

Reputation: 2122

Resetting ajax mock calls count in Jest tests

I have test structure represented below, my code uses ajax calls so I'm mocking as represented in the Jest tutorial:

describe('it behavior', function() {
  it('is as it is', function() {
    jQuery.ajax.mock.calls[0][0].success({
      data: []
    });
    ...
  });
  it('is is not as it was', function() {
    jQuery.ajax.mock.calls[1][0].success({
      data: [1, 2, 3]
    });
    ...
  });
});

What bothers me most is this jQuery.ajax.mock.calls[X][0] in every case, mostly because I made typos or forget to increment call number in mock.

Is it possible to reset mock call count in afterEach callback or some pattern for test organisation in that case? Preferably without any extra test dependencies.

Upvotes: 1

Views: 1033

Answers (1)

Shiva Nandan
Shiva Nandan

Reputation: 1845

Try this:

describe('something', function() {
  beforeEach(function() {
    jQuery.ajax = jest.genMockFunction()
  })

  it('does something', function() {
    // do something
  })
}

Upvotes: 2

Related Questions