Search code examples
javascriptnode.jsjestjstry-catchsupertest

How I can check error from try/catch block in Jest


How I can test my try / catch block in Jest if there is an error I'm sure that catch will handle? For example I want to test this code for reading a token from a separate file. I want to test my catch but the problem is that I don't know how to create a situation in Jest to make an error to handle in Jest.

const readToken = async () => {
try{
    const readFile = await fs.readFile('./apiData.json');
    const data = JSON.parse(readFile);
    
    return data.token;
    
}catch(err){
    throw err;
}
}

And this is my Jest code but is not working correct I think because in coverage show me that line with catch(err) is uncovered.

        it('should return catch error',async (done) => {
        try{
          
           await readToken()
            done()
        }catch(e){
          done(e);
        }
      })

Solution

  • You can mock fs.readFile to get it to throw an error for you:

      it('should handle a readFile error', async () => {
        jest.spyOn(fs, 'readFile')
         .mockImplementation(async () => { throw new Error('Some error'); });
        await expect(readToken()).rejects.toThrowError();
        fs.readFile.mockRestore()
      });
           
    

    You could do the same with JSON.parse:

      it('should handle a JSON.parse error', async () => {
        jest.spyOn(JSON, 'parse')
         .mockImplementation(() => { throw new Error('Some error'); });
        await expect(readToken()).rejects.toThrowError();
        JSON.parse.mockRestore()
      });
           
    

    Both of those tests would get the code in the catch block to run and bump up your test coverage. If you want to log the error to the console instead of throwing it again in the catch block, you can test for it like this:

      it('should handle a readFile error', async () => {
        jest.spyOn(fs, 'readFile')
         .mockImplementation(() => { throw new Error('Some error'); });
        jest.spyOn(console, 'error')
         .mockImplementation();
        await readToken();
        expect(console.error).toHaveBeenCalled();
        jest.restoreAllMocks();
      });