【问题标题】:How I can check error from try/catch block in Jest如何从 Jest 中的 try/catch 块中检查错误
【发布时间】:2020-12-30 20:47:41
【问题描述】:

如果出现错误,我如何在 Jest 中测试我的 try / catch 块,我确定 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;
}
}

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

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

【问题讨论】:

  • jestjs.io/docs/en/expect.html#tothrowerror?而你的捕获是完全没有意义的。
  • }catch(err){ throw err; } 是无操作的,一开始就不应该存在。
  • 那么你能告诉我更多我应该如何处理这个函数中的错误吗?
  • 您需要的方式。除了你,没有人可以决定。如果您需要它像当前一样抛出错误,请删除 try..catch。
  • 所以你想说在这个函数中没有必要写 try 和 catch 吗?非常感谢您的回答。

标签: javascript node.js jestjs try-catch supertest


【解决方案1】:

你可以模拟 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()
  });
       

你可以对 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()
  });
       

这两个测试都会让 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();
  });

【讨论】:

  • 非常感谢您的帮助。我想问你我是否也可以使用 jest.spyOn 从函数调用异步函数,例如 const function = async () => { try{ await somefunction() }catch(err){ console.error(err) ; } }
  • jest.spyOn 可用于跟踪对现有方法的调用,并在必要时模拟其实现或返回值。文档很好很详细:jestjs.io/docs/en/jest-object#jestspyonobject-methodname
  • 在您的示例中,您模拟 somefunction 的方式取决于它的声明位置;我必须查看更多代码。
  • 嗯,例如,如果我有这个函数: const refreshToken = async (token) => { try{ const decodeToken = jwt.decode(token, {complete: true}) const { payload } = decodeToken ; if (Date.now() >= payload.exp * 1000) { 等待 loginApi();返回等待 readToken(); } else { 返回令牌; } }catch(err){ console.error(err);我如何检查异步函数 loginApi() 是否工作正常?感谢您的时间和回答。
  • 在这种情况下你想模拟什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-16
  • 2016-05-29
  • 2016-05-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多