[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'

// 🐨 Write a test for the UnauthorizedError case
// 💰 const error = new UnauthorizedError('some_error_code', {message: 'Some message'})
// 💰 const res = {json: jest.fn(() => res), status: jest.fn(() => res)}

// 🐨 Write a test for the headersSent case
describe('errorMiddleware', () => {
  test('if res.headersSent, then pass down error', () => {
    const res = {
      headersSent: true,
      json: jest.fn(() => res),
      status: jest.fn(() => res),
    }
    const next = jest.fn()
    const error = new Error('error')
    errorMiddleware(error, null, res, next)
    expect(next).toHaveBeenCalledWith(error)
    expect(next).toHaveBeenCalledTimes(1)
    expect(res.json).not.toHaveBeenCalled()
    expect(res.status).not.toHaveBeenCalled()
  })

  test('error is UnauthorizedError', () => {
    const code = 'some_code'
    const message = 'Unauthorized'
    const error = new UnauthorizedError(code, {
      message,
    })
    // return res itself so that response are chainable
    // res.status().json()
    const res = {json: jest.fn(() => res), status: jest.fn(() => res)}
    const next = jest.fn(() => next)
    errorMiddleware(error, null, res, next)
    expect(next).not.toHaveBeenCalled()
    expect(res.status).toHaveBeenCalledWith(401)
    expect(res.status).toHaveBeenCalledTimes(1)
    expect(res.json).toHaveBeenCalledWith({
      code: error.code,
      message: error.message,
    })
    expect(res.json).toHaveBeenCalledTimes(1)
  })

  test('return 500 error', () => {
    const res = {json: jest.fn(() => res), status: jest.fn(() => res)}
    const error = new Error('Server error')
    const next = jest.fn()
    errorMiddleware(error, null, res, next)
    expect(next).not.toHaveBeenCalled()
    expect(res.status).toHaveBeenCalledWith(500)
    expect(res.status).toHaveBeenCalledTimes(1)
    expect(res.json).toHaveBeenCalledWith({
      message: 'Server error',
      stack: error.stack,
    })
    expect(res.json).toHaveBeenCalledTimes(1)
  })
})
复制代码

 

posted @   Zhentiw  阅读(92)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2016-08-05 [AngularJS] Accessible Button Events
2016-08-05 [React Native] Complete the Notes view
2014-08-05 [Javascript] Hositing
点击右上角即可分享
微信分享提示