$chiubaca / notes / fleeting / 2021-04-10
  • Revised mocking, spies and unit testing with Jest today. Revisiting fundamental testing concepts via some great blogs by Kent C Dodds:

    • But really, what is a JavaScript test?
    • But really, what is a JavaScript mock?
  • 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 like jest.fn((x)=> x) a.k.a jest.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 and mock.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 to watch 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.

Edit on GitHub ✏️

Hey I'm Alex Chiu 👋. These are my notes for literally anything.

I'm using the Zettelkasten method to organise my thoughts here.

My more polished writings are published to my main blog at chiubaca.com

Follow me on: Github / X (Twitter) / Mastodon / LinkedIn