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.

[Node & Testing] Intergration Testing with Node Express的更多相关文章

  1. 前端学习 node 快速入门 系列 —— 报名系统 - [express]

    其他章节请看: 前端学习 node 快速入门 系列 报名系统 - [express] 最简单的报名系统: 只有两个页面 人员信息列表页:展示已报名的人员信息列表.里面有一个报名按钮,点击按钮则会跳转到 ...

  2. node部署静态页面;node上线静态页面

    node部署静态页面上线 静态页面上线可以采用 nginx, tomcat或者node ,我们这里介绍下node部署静态页面 这里采用最简单的上线方式,我们就不用node + express + ej ...

  3. Node学习基础之安装node以及配置环境变量

    第一步去node官网下载nodejs 我放在D盘 接着在cmd输入node -v 就能得到node的版本号 还有npm -v 下来进入安装好的目录 nodejs目录 创建两个文件夹 node_cach ...

  4. Difference Between Performance Testing, Load Testing and Stress Testing

    http://www.softwaretestinghelp.com/what-is-performance-testing-load-testing-stress-testing/ Differen ...

  5. node.js系列笔记之node.js初识《一》

    node.js系列笔记之node.js初识<一> 一:环境说明 1.1 Linux系统CentOS 5.8 1.2 nodejs v0.10.15 1.3 nodejs源码下载地址 htt ...

  6. node.js入门系列(一)--Node.js简介

    什么是NodeJS JS是脚本语言,脚本语言都需要一个解析器才能运行.对于写在HTML页面里的JS,浏览器充当了解析器的角色.而对于需要独立运行的JS,NodeJS就是一个解析器. 每一种解析器都是一 ...

  7. 【node】使用nvm管理node版本

    写在前面 nvm(nodejs version manager)是nodejs的管理工具,如果你想快速更新node版本,并且不覆盖之前的版本:或者想要在不同的node版本之间进行切换: 使用nvm来安 ...

  8. 什么是Node.js?带你初识Node

    什么是Node.js Nodejs是一个基于Chrome v8引擎的JavaScript运行环境 Node.js使用了一个事件驱动,非阻塞式I/O的模型,使其轻量又高效. Node.js 的包管理器 ...

  9. Node.js的安装以及Node.js的模块管理

    索引: Node.js的安装以及Node.js的模块管理Node.js开发环境搭建以及对ES6的支持Node.js构建Vue.js项目Vue.js单文件组件的开发基于Vue.js的UI组件(Eleme ...

随机推荐

  1. MySQL外键的介绍

    在MySQL 3.23.44版本后,InnoDB引擎类型的表支持了外键约束. 1.MySQL中“键”和“索引”的定义相同,所以外键和主键一样也是索引的一种.不同的是MySQL会自动为所有表的主键进行索 ...

  2. POJ 3257 DP

    题意: 思路: 用vector存上本出发点能到的地方&成本&有趣指数(用结构体保存) 然后DP就好了 f[i][j]表示到了i 成本为j的有趣指数最大是多少 f[vec[i][k].e ...

  3. SQL SERVER 新增表、新增字段、修改字段 判断表是否存在

    // 新增之前判断表是否存在 IF NOT EXISTS (SELECT NAME FROM SYSOBJECTS WHERE ID = OBJECT_ID('tb_MessageHistory')) ...

  4. C/C++(C++类型增强)

    C++类型增强 类型检查更严格 把一个const类型的指针赋给非const类型的指针.c语言中可以通的过,但是在c++中则编不过去 const int a = 10; a = 100;//const修 ...

  5. Facebook下载总结

    Facebook是美国的一个社交网络服务网站,至今注册用户已超越20亿,月活用户更是惊人的突破3亿. 这样庞大的一个社交类网站,每日产生的社交数据当然也是非常可观,而这些社交数据,更接近口语,所以是比 ...

  6. vuex requires a Promise polyfill in this browser.--ie-vue-兼容处理日记

    1.ie9+报错vuex requires a Promise polyfill in this browser. 解决如下: npm install --save-dev -polyfill 修改c ...

  7. 学习《深度学习与计算机视觉算法原理框架应用》《大数据架构详解从数据获取到深度学习》PDF代码

    <深度学习与计算机视觉 算法原理.框架应用>全书共13章,分为2篇,第1篇基础知识,第2篇实例精讲.用通俗易懂的文字表达公式背后的原理,实例部分提供了一些工具,很实用. <大数据架构 ...

  8. nginx下修改svn配置

    最近公司的SVN服务器地址做了变更,而我用的操作系统是Ubuntu操作系统,我也不想把以前下载的代码重新进行修改,我想通过修改svn地址,应该可以,终于在网上通过查找资料,找到了解决的方法:      ...

  9. ReadyAPI/soapUI发送post请求json格式(带有中文字符),后台获取参数为空

    解决:请求编码格式默认为空,在"TestCase"的指定Step的Request Properties中, 改Encoding编码格式为UTF-8. 原文:soapUI发送post ...

  10. HOJ——T 2430 Counting the algorithms

    http://acm.hit.edu.cn/hoj/problem/view?id=2430 Source : mostleg Time limit : 1 sec Memory limit : 64 ...