单元测试是最小化的测试方式, 也是 TDD 的做法.
TDD 概念如下图:
通过测试反馈推进开发, ruby 是推崇这种编程方式的.
nodejs 有如下常用单元测试模块
1.mocha
Mocha 是一个基于 node.js 和浏览器的集合各种特性的 Javascript 测试框架, 并且可以让异步测试也变的简单和有趣. Mocha 的测试是连续的, 在正确的测试条件中遇到未捕获的异常时, 会给出灵活且准确的报告.
安装:
- 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.
进行测试:
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 方式生成的覆盖率报表.
其实单元测试在一些业务相对稳定, 但是逻辑情况比较复杂的项目中可以对于一些重要的代码进行全覆盖测试, 代码的稳健不光是靠编程技术和思维, 也需要一定的辅助测试, 在多人团队协作开发中愈发重要.
单元测试和编程语言类型无关, 它是一种良好的编程习惯.
来源: https://www.cnblogs.com/freephp/p/9380257.html