博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Node.js] Test Node RESTful API with Mocha and Chai
阅读量:4978 次
发布时间:2019-06-12

本文共 2374 字,大约阅读时间需要 7 分钟。

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.jsconst 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.jsconst 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();        });  });});

 

转载于:https://www.cnblogs.com/Answer1215/p/6784172.html

你可能感兴趣的文章
adb logcat
查看>>
VME总线 分类: 生活百科 2014-06-...
查看>>
数字信号相关和卷积
查看>>
[CSAPP]Bufbomb实验报告
查看>>
NaviActivity实现
查看>>
将已安装win10的系统重装(格式化C盘)
查看>>
C# 中的委托和事件
查看>>
CSS基础学习 17.CSS动画
查看>>
ATM机
查看>>
java反射
查看>>
js表单反显
查看>>
浪潮之巅阅读笔记二
查看>>
CSS内嵌样式实现打字效果
查看>>
从 HTTP 到 HTTPS 再到 HSTS
查看>>
CentOS7和CentOS6的区别
查看>>
关系型数据库事务二:隔离级别
查看>>
送给IT新人--多看、多问、多写
查看>>
MySQL常用命令
查看>>
今天端午节
查看>>
UOJ #79. 一般图最大匹配
查看>>