javascript - How I can check error from trycatch block in Jest - Stack Overflow

admin2025-04-10  0

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);
        }
      })

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);
        }
      })
Share Improve this question edited Sep 12, 2020 at 15:51 jonrsharpe 122k30 gold badges268 silver badges475 bronze badges asked Sep 12, 2020 at 15:49 VoytecVoytec 891 silver badge12 bronze badges 14
  • jestjs.io/docs/en/expect.html#tothrowerror? And your catch is totally pointless. – jonrsharpe Commented Sep 12, 2020 at 15:51
  • 2 }catch(err){ throw err; } is no-op and shouldn't be there in the first place. – Estus Flask Commented Sep 12, 2020 at 15:51
  • so can you tell me more how i should handle error in this function ? – Voytec Commented Sep 12, 2020 at 15:52
  • The way you need it. Nobody but you can decide that. If you need it to throw an error as is like it currently does, remove try..catch. – Estus Flask Commented Sep 12, 2020 at 15:56
  • So you wanna say that in this function is not necessary write try and catch ? thanks a lot for your answers. – Voytec Commented Sep 12, 2020 at 16:05
 |  Show 9 more ments

1 Answer 1

Reset to default 5

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();
  });
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744256861a238357.html

最新回复(0)