TDD尝试:nodejs单元测试

单元测试是最小化的测试方式,也是TDD的作法。html

TDD概念以下图:node

 

 

 

经过测试反馈推动开发,ruby是推崇这种编程方式的。express

nodejs有以下经常使用单元测试模块npm

1.mocha编程

Mocha是一个基于node.js和浏览器的集合各类特性的Javascript测试框架,而且可让异步测试也变的简单和有趣。Mocha的测试是连续的,在正确的测试条件中遇到未捕获的异常时,会给出灵活且准确的报告。json

安装: 浏览器

npm install -g mocha

 

const assert = require("assert");

describe('Array', function() {
    describe('#indexOf()', () => {
        it('should return -1 when the value is not present', () =>{
            assert.equal(-1, [1,2,3].indexOf(5));
            assert.equal(-1, [1,2,3].indexOf(0));
        });
    });
});

 

describe里面第一个参数为输出展现该测试段的目标,第二个参数为回调,里面写须要测试的case。ruby

进行测试:app

mocha filename

 

能够用于测试utils里面封装的经常使用函数,我的认为适合一些非http请求类代码测试。框架

2.should

require("should");

var name = "tonny";

 

describe("Name", function() {

    it("The name should be tonny", function() {

        name.should.eql("tonny");

    });

});

 

var Person = function(name) {

    this.name = name;

};

var zhaojian = new Person(name);

 

describe("InstanceOf", function() {

    it("Zhaojian should be an instance of Person", function() {

        zhaojian.should.be.an.instanceof(Person);

    });

 

    it("Zhaojian should be an instance of Object", function() {

        zhaojian.should.be.an.instanceof(Object);

    });

});

describe("Property", function() {

    it("Zhaojian should have property name", function() {

        zhaojian.should.have.property("name");

    });

});

 

should的用法让测试代码可读性更强。

3.supertest

用于http请求测试。

const request = require('supertest');
const express = require('express');

const app = express();

app.get('/user', function(req, res){
  res.send(200, { name: 'tobi' });
});

request(app)
  .get('/user')
  .expect('Content-Type', /json/)
  .expect('Content-Length', '20')
  .expect(200)
  .end(function(err, res){
    if (err) throw err;
  });

 

以前咱们遇到的中间件检查问题,就能够经过这个模块来进行不一样case的测试,保证接口逻辑上无误差。

 

4.istanbul 代码覆盖率检查工具

 

用法 :

istanbul cover filename

 

命令行模式会显示覆盖率状况。

以后会生成coverage文件夹,里面有html方式生成的覆盖率报表。

 

其实单元测试在一些业务相对稳定,可是逻辑状况比较复杂的项目中能够对于一些重要的代码进行全覆盖测试,代码的稳健不光是靠编程技术和思惟,也须要必定的辅助测试,在多人团队协做开发中愈发重要。

单元测试和编程语言类型无关,它是一种良好的编程习惯

相关文章
相关标签/搜索