如何检查 Jest 中 try/catch 块的错误

Vot*_*ech 1 javascript try-catch node.js supertest jestjs

如果出现我确定 catch 会处理的错误,我如何在 Jest 中测试我的 try / catch 块?例如,我想测试此代码以从单独的文件中读取令牌。我想测试我的捕获,但问题是我不知道如何在 Jest 中创建一个情况来在 Jest 中处理错误。

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

这是我的 Jest 代码,但我认为工作不正确,因为在覆盖范围内显示带有 catch(err) 的行未被发现。

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

小智 5

您可以模拟fs.readFile让它为您抛出错误:

  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()
  });
       
Run Code Online (Sandbox Code Playgroud)

您可以对 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()
  });
       
Run Code Online (Sandbox Code Playgroud)

这两个测试都会让 catch 块中的代码运行并提高测试覆盖率。如果您想将错误记录到控制台而不是在 catch 块中再次抛出错误,您可以像这样测试它:

  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();
  });
Run Code Online (Sandbox Code Playgroud)