[Node & Testing] Intergration Testing with Node Express

We have express app:

复制代码
import _ from 'lodash'
import faker from 'faker'
import express from 'express'
import bodyParser from 'body-parser'
import getTokenFromHeader from '../../src/routes/utils/get-token-from-header'

export default startServer

const users = _.times(20, () => faker.helpers.contextualCard())
const userAuth = {
  username: 'jane',
  password: 'I have a secure password',
}
const user = {
  token: 'Wanna-hear-a-secret?-I-sometimes-sing-in-the-shower!',
}

function startServer() {
  const app = express()

  app.use(bodyParser.json())

  function auth(req, res, next) {
    const token = getTokenFromHeader(req)
    if (!token || token !== user.token) {
      res.sendStatus(401)
    } else {
      next()
    }
  }

  const userRouter = express.Router()
  userRouter.get('/', (req, res) => {
    const {query: {limit = 20, offset = 0}} = req
    res.json({users: _.take(users.slice(offset), limit)})
  })

  // Preload user objects on routes with ':username'
  userRouter.param('username', (req, res, next, param) => {
    req.user = users.find(({username}) => username === param)
    next()
  })

  userRouter.get('/:username', (req, res) => {
    if (req.user) {
      res.json({user: req.user})
    } else {
      res.sendStatus(404)
    }
  })

  userRouter.post('/', auth, (req, res) => {
    users.unshift(req.body.user)
    res.json({user: users[0]})
  })

  userRouter.delete('/:username', auth, (req, res) => {
    users.splice(users.indexOf(req.user), 1)
    res.json({success: true})
  })

  const authRouter = express.Router()
  authRouter.post('/', (req, res) => {
    if (
      req.body.username === userAuth.username &&
      req.body.password === userAuth.password
    ) {
      res.json({user})
    } else {
      res.sendStatus(401)
    }
  })

  const apiRouter = express.Router()
  apiRouter.use('/users', userRouter)
  apiRouter.use('/auth', authRouter)

  app.use('/api', apiRouter)

  return new Promise(resolve => {
    const server = app.listen(3001, () => {
      resolve(server)
    })
  })
}
复制代码

As you can see, we wrap Express App into a function 'startServer' and export it as default export. The return value of this function is the server which wrap into a Promise.

 

The good part for doing this way is that we can start and stop server whenever we want to prevent menory leak or "ADDRESS IN USED" problem.

复制代码
import startServer from '../start-server'
import axios from 'axios'

let server

beforeAll(async () => {
    server = await startServer()
})

afterAll(done => server.close(done))

test('can get users', async () => {
    const user = await axios
        .get('http://localhost:3001/api/users')
        .then(response => response.data.users[0])

    // toMatchObject, to check whether user object
    // has 'name' prop which is a string
    // and 'username' prop which is a string
    // this is a subset, doesn't need to match all the object props
    expect(user).toMatchObject({
        name: expect.any(String),
        username: expect.any(String)
    })
})

// Test offset and limit should work
// first get 5 users
// then get last two users by given limit and offset
// then check tow users and equal to last tow user in five users.
test('get users, limit and offset should work', async () => {
    const fiveUsersPromise = axios
        .get('http://localhost:3001/api/users?limit=5')
        .then(response => response.data.users)
    const twoUsersPromise = axios
        .get('http://localhost:3001/api/users?limit=2&offset=3')
        .then(response => response.data.users)

    const response = await Promise
        .all([fiveUsersPromise, twoUsersPromise])
    const [fiveUsers, twoUsers] = response
    const [, , ,firstFiveUser, secondFiveUser] = fiveUsers
    const [firstTwoUser, secondTwoUser] = twoUsers
    expect(firstTwoUser).toEqual(firstFiveUser)
    expect(secondFiveUser).toEqual(secondTwoUser)
})
复制代码

 

In the test, we call 'beforeAll' to start the server and 'afterAll' to close the server.

 

posted @   Zhentiw  阅读(381)  评论(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-09-19 [Angular 2] Create Shareable Angular 2 Components
2016-09-19 [Angular 2] Import custom module
2016-09-19 [Angular 2] Understanding Pure & Impure pipe
点击右上角即可分享
微信分享提示