在我的 express
应用程序中,我像这样声明请求处理程序(此处已简化):
export const CreateProduct = async (req, res, next) => {
try {
// ProductModel is a sequelize defined model
const product = await ProductModel.create(req.body)
res.send(product)
} catch (err) {
// I have raygun setup as the error handler for express
// in this example, it will finally return 500
next(err)
}
}
然后像这样使用它:
import { CreateProduct } from './create_product'
export const ProductRouter = express.Router()
ProductRouter.post('/', CreateProduct)
但是,在运行我的测试时,nyc
/istanbul
会提示第 9
行是 Uncovered Line
(在我的示例中,它是 next(err)
函数),我该如何模拟示例中的错误?
最佳答案
更简单的方法是为您的 ProductModel
创建一个验证机制,当您使用无效数据创建产品时会抛出一些验证错误。
在您的 mocha 中,您将发送一个无效的产品主体,它会捕获您的next
。
关于node.js - 使用异步函数模拟请求错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46137617/