Search code examples
node.jsasync-awaitmocha.jsistanbulsupertest

Simulating request error with async function


In my express app, I declare request handlers like this(simplified here):

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)
  }
}

And then use it like so:

import { CreateProduct } from './create_product'

export const ProductRouter = express.Router()
ProductRouter.post('/', CreateProduct)

However, when running my test, nyc/istanbul will complain that line 9 is an Uncovered Line (in my example, it is the next(err) function), how do I go about simulating the error in my example?


Solution

  • The easier to go is to create a validation mechanism for your ProductModel, and when you create the product with invalid data throw some validation errors.

    And in your mocha you will send an invalid product body and it will catch your next.