node.js - How to trigger Express error middleware? -


i'm trying unit test piece of code in mocha:

app.use(function (err, req, res, next) {     console.error(err.stack)     res.status(500).send('something broke!') }) 

i don't know how request inside mocha unit test trigger it.

first break out middleware own file/function. sits, it's "integrated" express app. you're not testings only error middleware, express app instance extent.

with said, decouple error middleware express app:

src/middleware/error-handler.js

module.exports = (err, req, res, next) => {   console.error(err.stack)   res.status(500).send('something broke!') } 

you still .use() in main app.js or wherever setup express:

const express = require('express') const errorhandler = require('./src/middleware/error-handler') const app = express()  app.use(errorhandler) 

but we're free of express dependency , have simple function can isolate , test. below simple test jest can adjust work mocha.

__tests__/middleware/error-handler.test.js

const errorhandler = require('../../src/middleware')  describe('middleware.errorhandler', () => {   /**    * mocked express request object.    */   let req    /**    * mocked express response object.    */   let res    /**    * mocked express next function.    */   const next = jest.fn()    /**    * reset `req` , `res` object before each test ran.    */   beforeeach(() => {     req = {       params: {},       body: {}     }      res = {       data: null,       code: null,       status (status) {         this.code = status         return       },       send (payload) {         this.data = payload       }     }      next.mockclear()   })    test('should handle error', () => {     errorhandler(new error(), req, res, next)      expect(res.code).tobedefined()     expect(res.code).tobe(500)      expect(res.data).tobedefined()     expect(res.data).tobe('something broke!')   }) }) 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -