Spying on methods with Jest

Now, without implying that it is actually a good idea, let's see how we can spy on method calls using Jest. We'll verify that the checkResponseStatus method gets called as expected:

it('should call checkResponseStatus', async () => { 
    fetchMock.mockResponse( 
        JSON.stringify(dummyValidData), 
        {status: 200} 
    ); 

    const checkResponseStatusSpy = jest.spyOn(sut, 
"checkResponseStatus"); await sut.getAllCountries().catch(() => { fail("Should not fail"); }); expect(checkResponseStatusSpy).toHaveBeenCalledTimes(1); });

Using the jest.spyOn function, we tell Jest that we want to spy on the checkResponseStatus method. Then, after having called our getAllCountries method, we can verify whether the object that we're spying on has been called or not. In this case, the method is supposed to be called once.

You can learn more about Jest spy objects here: https://remarkablemark.org/blog/2018/04/10/jest-spyon-function

We'll stop our small incursion into the world of testing for now. As you can imagine though, there is a lot more ground to cover. Why don't you continue testing the other methods of the class to get more familiar with the subject?

Take some time now to go through the documentation of Jest in order to learn about the Jest object, how to mock functions, modules, and so on. It's a very useful resource. Finally, make sure to read the following article: https://medium.com/@rickhanlonii/understanding-jest-mocks-f0046c68e53c. It will teach you everything about Jest's support for mocking.