35

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]);
1
  • Did you found how to solve this with Jest? Could you provide an example?
    – Alexandre
    Commented Nov 20, 2017 at 12:53

4 Answers 4

54

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

3
  • 2
    const spy = jest .spyOn(jQuery, "ajax") .mockImplementation(({ success }) => success(payload));
    – emj365
    Commented Mar 5, 2019 at 7:26
  • 1
    @emj365 I've just tried this way and received TypeError: success is not a function. You can play with it here: codesandbox.io/s/kkq2377ll5. Just uncomment 12-14 lines.
    – ilyazub
    Commented Mar 6, 2019 at 8:34
  • i tried jest.spyOn.mockImplementation() it's work but not cover test coverage, since sinon stub yields cover test coverage. am i missing something here ?
    – martiendt
    Commented May 20, 2022 at 9:21
5

Jest provides jest.fn(), which has some basic mocking and stubbing functionality.

If you're experienced and comfortable with sinon you could still create Jest-based tests which use sinon test doubles. However you'll lose the convenience of built in Jest matchers such as expect(myStubFunction).toHaveBeenCalled().

1
  • 5
    Thanks. Is it restorable like sinon.stub.restore? The doc examples aren't really clear for me. It seems like you can only mock an entire module and then a func in it + they mention some sort of auto mocking option? Commented Jul 23, 2017 at 5:08
3

I was able to sub out jquery entirely by using mockReturnValue and jquery's $.Deferred. This allowed me to manually resolve my ajax calls and then the rest of the function would continue (and any chaining of .done() or .success() etc would execute.

Example:

const deferred = new $.Deferred();
$.ajax = jest.fn().mockReturnValue(deferred);

myClass.executeAjaxFunction();

const return_val = 7;

deferred.resolve(return_val)

Then if I have a function like

$.ajax({
    type: 'GET',
    url: '/myurl'
}).done((val) => {
    window.property = val;
});

The following test will pass

it('should set my property correctly', () => {
    expect(window.property).toBe(7);
});

Of course- you can skip the deferred part of this answer if you are trying to stub a non-jquery function. I came across this question that dealt with ajax and came up with this solution as a way to test a function that executes actions after an ajax call is complete using Jest.

2

Doing following two thing, got it working for me.

  1. Adding __esModule:true fixed this issue for me.

    jest.mock('module',()=>({ __esModule: true, default: jest.fn() }));

  2. Moving the mocking part before the describe. (Just after the imports.)

    //moving it to before the describe -> jest.mock(...); describe('', ...);

Hope this helps somebody.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.