-
Jest mocks and spies seems to make a bit more sense today.
- Mocking is required for libs, to let Jest overide the functionality. With jest we often need to use
jest.mock()
. For example with axios we would dojest.mock('axios')
. - When TS is in play we need to assert some special Jest types to make it play nice like so:
const mockedAxios = axios as jest.Mocked<typeof axios>
This provides us a with mocked instance of axios where we can overide specfic functions of axios like
.get
and.post
with mock jestsmockResolvedValue
a nice way of returning a fake resolved promise response.- when doing this, itβs proably not so important to assert the fake input and responses. With spies, we can watch when these axios properties were called and how many times. The syntax looks like this:
const axiosSpy = spyOn(mockedAxios, "get"); //first args is the parent object, second is the property we want to watch // not sure what you want to do if you want to just watch the parent object π€
- The spied instance lets us assert other useful things
expect(axiosSpy).toHaveBeenCalledTime(2); expect(axiosSpy).toHaveBeenCalledWith("./jsonEndpoint");
- Mocking is required for libs, to let Jest overide the functionality. With jest we often need to use