zoukankan      html  css  js  c++  java
  • 前端之 —— node.js摸爬打滚之路(二)

    这篇主要学习:

    • 测试框架mocha;
    • 断言库:should;
    • 测试率覆盖工具 istanbul;

    创建并进入lesson3:

    mkdir lesson3 && lesson3

    创建main.js并编写测试函数:

    var fibonacci = function(n) {
        if(typeof n !== 'number'){
            throw new Error('n should be a Number')
        }
        if(n < 0){
            throw new Error('n should >= 0')
        }
        if(n > 10){
            throw new Error('n should <= 10')
        }
        if(n === 0){
            return 0
        }
        if(n === 1){
            return 1
        }
        return fibonacci(n-1) + fibonacci(n-2)
    }
    
    if(require.main === module){
        var n = Number(process.argv[2])
        console.log('fibonacci('+ n +') is',fibonacci(n))
    }
    
    exports.fibonacci = fibonacci

    lesson3下创建test文件夹,并创建main.test.js:

    mkdir test && cd test && echo.>main.test.js

    在main.test.js编写测试用例:

    var main = require('../main')
    var should = require('should')
    
    describe('test/main.test.js',function(){
        it('should equal 0 when n === 0', function(){
            main.fibonacci(0).should.equal(0)
        })
        it('should equal 1 when n === 1', function(){
            main.fibonacci(1).should.equal(1)
        })
        it('should equal 55 when n === 10', function(){
            main.fibonacci(10).should.equal(55)
        })
        it('should throw when n > 10', function (){
        (function (){
          main.fibonacci(11)
        }).should.throw('n should <= 10')
      })
        it('should throw when n < 0', function(){
            (function(){
                main.fibonacci(-1)
            }).should.throw('n should >= 0')
        })
        it('should throw when n isnt Number', function(){
            (function(){
                main.fibonacci('逗比')
            }).should.throw('n should be a Number')
        })
    })

    cmd输出:

    mocha

    如下图所示则完成测试:

    安装一个 istanbul:

    cnpm i istanbul -g

    执行:

    istanbul cover _mocha

    (注:如果window下报找不到_mocha文件的错,就找到你电脑中mocha安装目录下的_mocha文件的位置替代_mocha,例:istanbul cover C:Users[用户名]AppDataRoaming pm ode_modulesmochain\_mocha)

    可以看到,其中的分支覆盖率是 91.67%,行覆盖率是 87.5%。

  • 相关阅读:
    客户端发现响应内容类型为“text/html”,但应该是“text/xml”
    [转]AJAX Control Toolkit 介绍及构建开发环境
    kafka删除topic详解
    influxdb问题解决
    logback配置
    kafka环境搭建测试
    Hdu 1753 大明A+B <高精度小数相加>
    POJ 1966 <点连通度>
    POJ 2446 Chessboard 二分图的最大匹配 <建图>
    Hlg 1522 子序列的和 <单调队列>
  • 原文地址:https://www.cnblogs.com/geewonii/p/7172962.html
Copyright © 2011-2022 走看看