如何使用 jest 测试 javascript 中的 try catch 代码并在 express 中包含带有中间件的 next() 调用?
How to test try catch code in javascript using jest and including a next() call with middleware in express?
我正在创建一个 API,我想知道如何测试 try catch 块。我想确保块捕获的错误正在将 throw next() 快速传递给下一个中间件。
这是一个例子,这是我对 POST 方法的回调:
function create (req, res, next) {
try {
const data = {}
response(req, res, data, 201)
} catch (error) {
next(error)
}
}
我想测试调用 next。我打算使用 sinon 来做,但我想模拟错误并验证捕获错误。
这是我开玩笑报道的屏幕。
如果重现实际错误需要付出太多努力,我就不会涵盖该声明。
感谢 Jest 的模拟函数,可以 监视 函数、方法和模块并临时替换它的实现和 return 值。
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
请注意,此语法适用于函数。如果这是来自 class 的方法,那么它将是 jest.spyOn(YourClass.prototype, 'methodNameInsideQuotes')
。 Jest 有据可查,您应该在没有黑客的情况下使用它。
我正在创建一个 API,我想知道如何测试 try catch 块。我想确保块捕获的错误正在将 throw next() 快速传递给下一个中间件。
这是一个例子,这是我对 POST 方法的回调:
function create (req, res, next) {
try {
const data = {}
response(req, res, data, 201)
} catch (error) {
next(error)
}
}
我想测试调用 next。我打算使用 sinon 来做,但我想模拟错误并验证捕获错误。
这是我开玩笑报道的屏幕。
如果重现实际错误需要付出太多努力,我就不会涵盖该声明。
感谢 Jest 的模拟函数,可以 监视 函数、方法和模块并临时替换它的实现和 return 值。
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
请注意,此语法适用于函数。如果这是来自 class 的方法,那么它将是 jest.spyOn(YourClass.prototype, 'methodNameInsideQuotes')
。 Jest 有据可查,您应该在没有黑客的情况下使用它。