[Node.js] Test Node RESTful API with Mocha and Chai
2023-09-14 08:59:18 时间
In this lesson, we will use Chai's request method to test our Node application's API responses.
By the end of this lesson, you will know how to:
- install the prerequisites to use mocha and chai in your application
- test for HTTP status response codes
- test for a string of text on a page
- test for a json response and validate the properties of the object
- write tests that not only verify the response of your application, but the behavior as well
const mockRouter = require('./routes/mock');
app.use('/mock', mockRouter);
// routers/mock.js const express = require('express'); const router = express.Router(); router .get('/', (req, res, next) => { res.status(200) .json({ title: 'Mock test' }) }) .post('/', (req, res, next) => { const { v1, v2 } = req.body; if (isNaN(Number(v1)) || isNaN(Number(v2))) { res.status(400) .json({ 'msg': 'You should provide numbers' }); } else { const result = Number(v1) + Number(v2); res.status(200) .json({ result }); } }); module.exports = router;
// test/mock_test.js const chai = require('chai'); const chaiHttp = require('chai-http'); const should = chai.should(); const server = require('../../src/app'); chai.use(chaiHttp); describe('/mock GET', () => { it('should return json', (done) => { chai.request(server) .get('/mock') .end((err, res) => { res.should.have.status(200); res.body.should.have.property('title') .and .that .equal('Mock test'); done(); }) }); it('should return right value', (done) => { chai.request(server) .post('/mock') .set('content-type', 'application/json') .send({ v1: 2, v2: 3 }) .end((err, res) => { res.should.have.status(200); res.body.should.have.property('result').that.equals(5); done(); }); }); it('should return 400 error', (done) => { chai.request(server) .post('/mock') .set('content-type', 'application/json') .send({ v1: 'tow', v2: 'three' }) .end((err, res) => { res.should.have.status(400); res.body.should.have.property('msg').that.contains('provide numbers'); done(); }); }); });
相关文章
- js面试题及答案2020_JS面试题大全
- JS跳转代码_js中跳转页面路径
- php 中js跳转页面跳转页面,js跳转代码_PHP页面跳转 Js页面跳转代码[通俗易懂]
- 深入理解Node.js的进程与子进程
- 如何使用jscythe并通过Node.js的Inspector机制执行任意JS代码
- 【源码】PDF.js批注注释插件库(纯JS). 创建和保存PDF批注(PDF 高亮/签名/插图/截屏/文本框/画笔/多边形)-pdf.js
- JS动态引入js、CSS动态创建script/link/style标签详解编程语言
- Linux环境下配置Node.js(linux配置node)
- 解除 Linux 上的 Node.js 安装(linux卸载node)
- 快速在Linux平台上安装Node.js(node安装linux)
- 使用Node.js实现对MSSQL数据库的连接(node连接 mssql)
- 利用Node.js封装MSSQL的尝试(node mssql封装)
- Redis中的订阅机制及其在JS中的应用(redis 订阅 js)
- 把JS与CSS写在同一个文件里的书写方法
- CSS和JS标签style属性对照表(方便js开发的朋友)
- js判断运行jsp页面的浏览器类型以及版本示例
- js获取url参数代码实例分享(JS操作URL)
- js正则表达式学习笔记之匹配字符串
- js实现div弹出层的方法