stubbing a function using jest

后端 未结 3 1690
一生所求
一生所求 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:15

    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

提交回复
热议问题