【问题标题】:How to test try catch code in javascript using jest and including a next() call with middleware in express?如何使用 jest 在 javascript 中测试 try catch 代码并在 express 中包含带有中间件的 next() 调用?
【发布时间】:2022-01-15 14:10:32
【问题描述】:

我正在创建一个 API,我想知道如何测试 try catch 块。我想确保块的错误捕获正在将 throw next() 快速传递给下一个中间件。

这里是一个例子,这是我对 POST 方法的回调:

function create (req, res, next) {
  try {
    const data = {}
    response(req, res, data, 201)
  } catch (error) {
    next(error)
  }
}

我想测试下一个是否被调用。我打算使用 sinon 来做,但我想模拟错误并验证捕获错误。

这是我开玩笑的报道画面。

【问题讨论】:

  • 存根response函数并使其抛出错误。

标签: node.js express unit-testing try-catch sinon


【解决方案1】:

如果重现实际错误需要付出太多努力,我就不会涵盖该声明。

感谢 Jest 的模拟函数,可以监视函数、方法和模块,并临时替换它的实现和返回值。

https://jestjs.io/docs/mock-function-api

应该是这样的

// replace the implementation for your stub
const spy = jest.spyOn(response).mockImplementation(() => { throw new Error(); });
...
expect(spy).toHaveBeenCalled();
spy.mockRestore(); // restore the implementation

请注意,这种语法适用于函数。如果这是一个类的方法,那么它将是jest.spyOn(YourClass.prototype, 'methodNameInsideQuotes')。 Jest 有据可查,您应该在没有任何黑客攻击的情况下使用它。

【讨论】:

    猜你喜欢
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-04
    • 2020-05-17
    • 2019-08-12
    相关资源
    最近更新 更多