[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.
[Node & Testing] Intergration Testing with Node Express的更多相关文章
- 前端学习 node 快速入门 系列 —— 报名系统 - [express]
其他章节请看: 前端学习 node 快速入门 系列 报名系统 - [express] 最简单的报名系统: 只有两个页面 人员信息列表页:展示已报名的人员信息列表.里面有一个报名按钮,点击按钮则会跳转到 ...
- node部署静态页面;node上线静态页面
node部署静态页面上线 静态页面上线可以采用 nginx, tomcat或者node ,我们这里介绍下node部署静态页面 这里采用最简单的上线方式,我们就不用node + express + ej ...
- Node学习基础之安装node以及配置环境变量
第一步去node官网下载nodejs 我放在D盘 接着在cmd输入node -v 就能得到node的版本号 还有npm -v 下来进入安装好的目录 nodejs目录 创建两个文件夹 node_cach ...
- Difference Between Performance Testing, Load Testing and Stress Testing
http://www.softwaretestinghelp.com/what-is-performance-testing-load-testing-stress-testing/ Differen ...
- node.js系列笔记之node.js初识《一》
node.js系列笔记之node.js初识<一> 一:环境说明 1.1 Linux系统CentOS 5.8 1.2 nodejs v0.10.15 1.3 nodejs源码下载地址 htt ...
- node.js入门系列(一)--Node.js简介
什么是NodeJS JS是脚本语言,脚本语言都需要一个解析器才能运行.对于写在HTML页面里的JS,浏览器充当了解析器的角色.而对于需要独立运行的JS,NodeJS就是一个解析器. 每一种解析器都是一 ...
- 【node】使用nvm管理node版本
写在前面 nvm(nodejs version manager)是nodejs的管理工具,如果你想快速更新node版本,并且不覆盖之前的版本:或者想要在不同的node版本之间进行切换: 使用nvm来安 ...
- 什么是Node.js?带你初识Node
什么是Node.js Nodejs是一个基于Chrome v8引擎的JavaScript运行环境 Node.js使用了一个事件驱动,非阻塞式I/O的模型,使其轻量又高效. Node.js 的包管理器 ...
- Node.js的安装以及Node.js的模块管理
索引: Node.js的安装以及Node.js的模块管理Node.js开发环境搭建以及对ES6的支持Node.js构建Vue.js项目Vue.js单文件组件的开发基于Vue.js的UI组件(Eleme ...
随机推荐
- Tomcat部署项目修改浏览器上猫咪头像
一.发现问题用tomcat部署项目,在浏览器标签也上发现了tomcat猫咪图.要把这个图修改掉. 二.解决问题apache-tomcat-5.5.28\webapps\ROOT下的ico文件,将需要替 ...
- mvc下是如何传值的
最近在开发一个项目,用的是mvc框架,现将mvc会用到的常用传值方法总结如下: 在讲传递参数方法之前,先简单介绍一下MVC路由及运行机制. 首先,Web 浏览器向服务器发送一条URL 请求,如 ...
- 目前常见的三种SQL分页方式:
--top not in方式 select top 条数 * from tablename where Id not in (select top 条数*页数 Id from tablename) - ...
- SQL函数_Charindex()
1 charindex()函数的作用是用于发现目标字符串第一次出现在源字符串中出现的开始位置. 语法如下 : select charinde(目标字符串,列名或字符串[,起始位置]) from 表名
- 安装完Python之后,如何设置Python环境变量
人生苦短,我用Python.最近有许多加群的萌新在咨询Python安装的事宜,Python安装问题不大,可以戳这篇文章:.本以为安装Python之后就可以万事大吉,高枕无忧了,往命令行中输入pytho ...
- 【转】一篇关于32位Linux内核使用大内存的文章——Hugemem Kernel Explained &nb
红旗DC系列Linux操作系统(x86平台)中带有四类核心: UP (支持单内核) SMP (支持多内核) hugemem Icc* (用intel C编译器编译的核心) 其中hugemem核心往往引 ...
- 【VC++学习笔记五】SDI|MDI的全屏显示
一.Mainframe中添加一个记录是否全屏状态的变量BOOL m_bFullScreen. 二.工具栏添加一个按钮,进行全屏的操作,响应事件函数写在Mainframe中. 三.在响应函数中,添加如下 ...
- Netty In Action中文版 - 第七章:编解码器Codec
http://blog.csdn.net/abc_key/article/details/38041143 本章介绍 Codec,编解码器 Decoder,解码器 Encoder,编码器 Netty提 ...
- C# Excel文件导入操作
Excel文件导出的操作我们经经常使用到,可是讲一个Excel文档导入并显示到界面还是第一次用到. 以下简介下在C#下怎样进行Excel文件的导入操作. 首先加入两个引用 using System.I ...
- vim-插入格式化时间
最近一直在搞vimrc的配置.其中有一点就是,我想要实现代码快速注释的功能.而这个功能中的一个关键点就是,我要获得系统当前的时间,然后插入到我的注释里面.我知道vimrc支持shell命令,既使用:r ...