Search code examples
javascriptunit-testingtestingjestjs

Run Jest tests multiple times if it fails


I'm using Jest for testing some API endpoints, but these endpoints might fail falsy at some times, because of network issues and not my program bugs. So I want to do the test again multiple times (5 times for example) with a delay, and if all of these tries failed, Jest should report a failure.

What is the best way to achieve this? Does Jest or other libraries provide a solution? Or should I write my own program with something like setInterval?


Solution

  • For testing you should not ideally be making network calls as they slow down your tests. Moreover you might be communicating to an external API which ideally should not be part of your test code. Also can lead to false negatives as already observed by you. You can do something like below:

    async function getFirstMovieTitle() {
      const response = await axios.get('https://dummyMovieApi/movies');
      return response.data[0].title;
    }
    

    For testing above network call you should mock your axios get request in your test. To test the above code, you should

    jest.mock('axios');
    
    it('returns the title of the first movie', async () => {
      axios.get.mockResolvedValue({
        data: [
          {
            title: 'First Movie'
          },
          {
            title: 'Second Movie'
          }
        ]
      });
    
      const title = await getFirstMovieTitle();
      expect(title).toEqual('First Movie');
    });
    
    

    Try to read more about mocking in jest to understand better