-
Revised mocking, spies and unit testing with Jest today. Revisiting fundamental testing concepts via some great blogs by Kent C Dodds:
-
jest.fn()
, lets you mock the implementation of method that might be expensive or flakey to run. Usually you write a mock implementation to return some fake data likejest.fn((x)=> x)
a.k.ajest.fn(<any arbitary function>)
-
Kent D Dodds talks about ‘monkey patching’ using
jest.fn()
which term which means to overide the exsiting functionality, which is useful when we need to mock a library. We can simply overide the implementation with our mock.const originalGetWinner = utils.getWinner; utils.getWinner = jest.fn((p1, p2) => p2);
-
When using plain JS,
utils.getWinner
gets new properties adding in by jest such as.mock.instances
,.mock.calls
andmock.results
which are using for a range of different asserations like what arguments were passed in, where the original instance from and what the actual result was. -
TS will complain that
mock
does not exist on the property, to get around this we can use a Jest spy instead. which a way towatch
when the function/method was called. it looks like this: -
utils.getWinner = jest.fn((p1, p2) => p2); const spy = jest.spyOn(utils, "getWinner"); const winner = thumbWar("alex", "jenny"); expect(spy).toHaveBeenCalledTimes(2); expect(spy).toHaveBeenCalled(); spy.mock.calls.forEach((args) => { expect(args).toEqual(["alex", "jenny"]); });
it offers all the same functionality that is exposed on a
.mock
property.
-