[Unit Testing + Jest + Node server] Testing a Node middleware with Jest

Code:

import {UnauthorizedError} from 'express-jwt'

function errorMiddleware(error, req, res, next) {
  if (res.headersSent) {
    next(error)
  } else if (error instanceof UnauthorizedError) {
    res.status(401)
    res.json({code: error.code, message: error.message})
  } else {
    res.status(500)
    res.json({
      message: error.message,
      // we only add a `stack` property in non-production environments
      ...(process.env.NODE_ENV === 'production' ? null : {stack: error.stack}),
    })
  }
}

export default errorMiddleware

 

Test:

  • Function have been called with
  • Function have been called Times
  • Function have not been called
import {UnauthorizedError} from 'express-jwt'
import errorMiddleware from '../error-middleware'

// 
上一篇:jest在node中使用:jest Cannot use import statement outside a module


下一篇:[Unit testing + Jest] Use jest-in-case to Reduce Duplication and Improve Test Titles