stubbing a function using jest

后端 未结 3 1651
一生所求
一生所求 2021-02-05 03:49

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 un

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-05 04:32

    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.

提交回复
热议问题