should + mocha 搭建简单的单元测试环境

快速搭建测试环境,详细用法请百度和访问两者的github

mocha:

http://mochajs.org/

should:

https://github.com/shouldjs/should.js

http://shouldjs.github.io/#assertion-false

第三方学习资源:

# 测试框架 Mocha 实例教程
http://www.ruanyifeng.com/blog/2015/12/a-mocha-tutorial-of-examples.html

# 单元测试:使用mocha和should.js搭建nodejs的单元测试
https://my.oschina.net/bosscheng/blog/189667

安装:

npm install should mocha --save-dev
npm install mocha -g
 
新建api.test.js文件夹
 
api.test.js代码
"use strict";
const should = require('should')
var rp = require('request-promise');


describe('API', () => {

    const API_SERVER = 'http://192.168.8.208:8010/api/project/DoOld'
    const a = 'abc';

    it('test110', () => {
        a.should.eql('abc');
    })
    
    it('test120', done => {
        a.should.eql('abc');
        done();
    })
    
    it('userInfo', done => {        
        rp.post(API_SERVER, {form:{
                UserId: 'A6F28BA9C3BDA307',
                MethodName: 'user_info'
        }}).then( (body) => {
            let json = JSON.parse(body);
            json.ReturnMessage.should.eql("成功")
            done()
        }).catch(function (err) {
            console.log(err)
        });
    })
})

上面这段代码,就是测试脚本,它可以独立执行。测试脚本里面应该包括一个或多个describe块,每个describe块应该包括一个或多个it块。

describe块称为"测试套件"(test suite),表示一组相关的测试。它是一个函数,第一个参数是测试套件的名称("加法函数的测试"),第二个参数是一个实际执行的函数。

it块称为"测试用例"(test case),表示一个单独的测试,是测试的最小单位。它也是一个函数,第一个参数是测试用例的名称,第二个参数是一个实际执行的函数。

输入命令: mocha api.test.js

 
原文地址:https://www.cnblogs.com/CyLee/p/6564175.html