Erasing a function with a joke

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

eg -

sinon.stub(jQuery, "ajax").yieldsTo("success", [1, 2, 3]);
+4
source share
2 answers

Jest provides jest.fn (), which has some basic functions of bullying and stubbing.

, Jest, sinon. Jest, expect(myStubFunction).toHaveBeenCalled().

+2

jest jest.spyOn:

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

:

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);

codesandbox: https://codesandbox.io/s/018x609krw?expanddevtools=1&module=%2Findex.test.js&view=editor

+1

Source: https://habr.com/ru/post/1682050/


All Articles