nodejs 单元测试

    之前项目开发因为改进度,基本都是粗放式开发。为了提高代码质量,单元测试是必不可少的。

    针对restful api ,用supertest 测试框架。针对nodejs,引入mocha 和should 可以方便编写单元测试。

    首先谈谈supertest,它封装了mocha和expect 模块。用法也比较简洁,例子:

    

var request = require('supertest');
var express = require('express');
let should=require('should');
 

var app = require('../app');
var port = process.env.PORT || 3000;
app.set('port', port);
describe('supertest 验证', function() {

  beforeEach(function() {
    console.log('before every test in every suit');
  });

  it('get 请求', function(done) {
    request(app)
      .get('/')
      .set('Cache-control', 'no-cache')
      .expect(200, done);
  });

  it('Post 请求', function(done) {
    request(app)

      .post('/sayHello')
      .set('Content-Type', 'application/json')
      .send({
        username:'ryan',
        password:'chen'
      })
      .expect('Content-Type', /json/)
      .expect(200,{message:"ryan你好"}, done);
  });

});

     如上代码所示,整体看是比较easy清爽的。可以设置header和对比返回值,至于token的验证,在测试时根据环境变量取消即可。

   

 should 是个好同志,可以帮助我们方便比较。至于用法,如下:

 1 describe('should test', function () {
 2   "use strict";
 3   beforeEach(function () {
 4   });
 5   it('ok', function (done) {
 6     true.should.be.ok;
 7     (5).should.be.exactly(6).and.be.a.number;
 8     done();
 9   });
10   it('true',function (done) {
11     true.should.be.true;
12     'true'.should.not.be.true;
13     done();
14   });
15   //content compare,not reference
16   it('eql', function () {
17     ({ foo: 'bar',num:1 }).should.eql({ foo: 'bar',num:1});
18     //[1, 2, 3].should.eql({ '0': 1, '1': 2, '2': 3 });
19 
20   });
21   //to be exactly,
22   it('equal',function () {
23     (4).should.equal(4);
24     'test'.should.equal('test');
25     [1,2,3].should.be.not.exactly([1,2,3]);
26   });
27   //>= or <=
28   it('within', function () {
29     (5).should.be.within(5, 10).and.within(5, 5);
30     (5).should.be.above(0);
31   });
32   //.Infinity
33   it('infinity', function () {
34     (1/0).should.be.Infinity;
35   });
36   //instanceof
37   it('instanceof', function () {
38     let ball=new Ball(11,"red");
39     ball.should.be.an.instanceOf(Ball);
40     [].should.be.an.instanceof(Array);
41   });
42 
43   it('properties',function () {
44     let ball=new Ball(11,"red");
45 
46     ball.should.have.properties('color');
47     ball.should.have.properties({size:11,color:"red"});
48   });
49   it('empty', function () {
50     [].should.be.empty;
51     ''.should.be.empty;
52     ({}).should.be.empty;
53     (function() {
54       arguments.should.be.empty;
55     })();
56   });
57   it('containEql', function () {
58     'hello boy'.should.containEql('boy');
59     [1,2,3].should.containEql(3);
60     [[1],[2],[3]].should.containEql([3]);
61     [[1],[2],[3, 4]].should.not.containEql([3]);
62   });
63   //regex
64   it('regex or function', function () {
65     ['a', 'b', 'c'].should.match(/[a-z]/);
66     (5).should.match(function(n) { return n > 0; });
67     (5).should.not.match(function(n) { return n < 0; });
68   });
69   it('match each', function () {
70     [10, 11, 12].should.matchEach(function(it) { return it >= 10; });
71   });
72 
73   it('exception', function () {
74     (function(){
75       throw new Error('fail');
76     }).should.throw();
77   });
78 
79   it('status',function () {
80      //res.should.have.status(200);
81      //res.should.have.header('Content-Length', '123');
82     //res.should.be.json
83 
84   })
85 
86 });
87 
88 class Ball
89 {
90   constructor(size,color)
91   {
92     Object.assign(this,{size,color});
93   }
94 }
View Code

  可以在控制台,用mocha 命令 测试,会默认找项目根目录下test文件夹,所以单元测试要放到此文件下。执行后,会测试当前文件夹下所有的单元测试:

  

  开发工具如果用的是webstorm,有个比较方便的插件。可在插件里面搜 nodejs,安装后,可在启动配置中添加mocha,

 

 配置后,直接启动

 

 可以看到,这样的话可以选择其中某个测试用例测试,比输入脚本方便了好多。bingo

原文地址:https://www.cnblogs.com/ryansecreat/p/6150678.html