zoukankan      html  css  js  c++  java
  • Mocha单元测试简易教程

    引言
    根据自己学习及使用mocha工具的心得与经验写了这份简易教程,希望对有需要的同学们能够有所帮助。
    需要做的准备
    1.安装Node.js 安装教程
    2.安装Mocha工具 安装教程
    开始上手
    1.编写脚本
    下面是一个非常基本的JS模块代码add.js,我们针对这个模块写一个测试脚本。

    // add.js

    function add(x, y) {return x + y;}
    module.exports = add;


    脚本的代码命名为add.test.js(在文件名中增加test),代码如下。

    // add.test.js

    var add = require('./add.js');

    var expect = require('chai').expect;

    describe('加法模块测试', function() {
    it('1 加 1 应该等于 2', function() {
    expect(add(1, 1)).to.be.equal(2);
    });
    });


    2.断言语句的使用

    var expect = require('chai').expect;
    这是一句断言,它引用“chai”断言库。 常用的断言语句有
    // 相等或不相等

    expect(4 + 5).to.be.equal(9);

    expect(4 + 5).to.be.not.equal(10);

    expect(foo).to.be.deep.equal({ bar: 'baz' });

    // 布尔值为true
    expect('everthing').to.be.ok;
    expect(false).to.not.be.ok;

    // typeof
    expect('test').to.be.a('string');
    expect({ foo: 'bar' }).to.be.an('object');
    expect(foo).to.be.an.instanceof(Foo);

    // include
    expect([1,2,3]).to.include(2);
    expect('foobar').to.contain('foo');
    expect({ foo: 'bar', hello: 'universe' }).to.include.keys('foo');

    // empty
    expect([]).to.be.empty;
    expect('').to.be.empty;
    expect({}).to.be.empty;

    // match
    expect('foobar').to.match(/^foo/);

    3.基本用法 使用Mocha工具运行测试脚本。进入测试脚本所在的目录,在终端执行如下命令:
    $ mocha add.test.js

    加法模块测试
    ✓ 1 加 1 应该等于 2

    1 passing (8ms)


    出现上述结果说明测试成功。

  • 相关阅读:
    大佬讲话听后感
    P1226快速幂取余
    对拍
    P1017 进制转换
    P1092 虫食算 NOIP2002
    P1003 铺地毯
    P1443 马的遍历
    P1032 字串变换
    P1379 八数码问题
    2-MAVEN 基本命令
  • 原文地址:https://www.cnblogs.com/wwph/p/13799984.html
Copyright © 2011-2022 走看看