node.js - 使用异步函数模拟请求错误

标签 node.js async-await mocha.js istanbul supertest

在我的 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/

相关文章:

node.js - 大文件的上传/下载如何影响 Node.js 中的事件循环

javascript - Node JS 读取表单数据

javascript - 在 mocha 中断言函数失败 "assert"导致超时而不是失败

javascript - 我在使用毯子的 Mocha 代码覆盖率中获得 0% 覆盖率 0 SLOC

node.js - 找不到模块 './lib/should'

node.js - Bower 未被识别为内部或外部命令

node.js - 阻止 EBS Linux 2 (Node.js) 尝试执行 npm 安装?

javascript - 在 promise 中有多个异步等待

Javascript函数在执行前返回值

c# - 针对特定异常的单元测试异步方法