[Node.js] Test Node RESTful API with Mocha and Chai
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(); }); }); });
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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-04-29 [Typescript] Introduction to Generics in Typescript
2015-04-29 [Whole Web, Node.js, PM2] Restarting your node.js app on code change using pm2
2015-04-29 [Whole Web, Node.js PM2] Loggin with PM2
2015-04-29 [Whole Web, Node.js, PM2] Configuring PM2 for Node applications
2015-04-29 [ES6] 22. Const
2015-04-29 [ES6] 21. ESNext, ES6-Shim & Node
2015-04-29 [ES6] 20. Polyfills