stubbing a function using jest

Mattan Bitner picture Mattan Bitner · Jul 22, 2017 · Viewed 22.8k times · Source

is there a way to stub a function using jest API? I'm used to working with sinon stub, where I can write unit-tests with stubs for any function call coming out of my tested unit- http://sinonjs.org/releases/v1.17.7/stubs/

for example-

sinon.stub(jQuery, "ajax").yieldsTo("success", [1, 2, 3]);

Answer

Ilya Zub picture Ilya Zub · Apr 13, 2018

With jest you should use jest.spyOn:

jest
  .spyOn(jQuery, "ajax")
  .mockImplementation(({ success }) => success([ 1, 2, 3 ]));

Full example:

const spy = jest.fn();
const payload = [1, 2, 3];

jest
  .spyOn(jQuery, "ajax")
  .mockImplementation(({ success }) => success(payload));

jQuery.ajax({
  url: "https://example.api",
  success: data => spy(data)
});

expect(spy).toHaveBeenCalledTimes(1);
expect(spy).toHaveBeenCalledWith(payload);

You can try live example on codesandbox: https://codesandbox.io/s/018x609krw?expanddevtools=1&module=%2Findex.test.js&view=editor