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)


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

  • 相关阅读:
    BZOJ 1143 [CTSC2008]祭祀river
    BZOJ 3997 [TJOI2015]组合数学
    BZOJ 3996 [TJOI2015]线性代数
    BZOJ 4553 [Tjoi2016&Heoi2016]序列
    微信开发之密文模式 mcrypt_module_open 走不过
    JS JSON & ARRAY 遍历
    linux ftp服务器配置(Ubuntu)
    thinkphp 吐槽篇
    游戏--疯狂猜字随机混乱正确答案逻辑
    PHP 批量去除BOM头;此文转载;
  • 原文地址:https://www.cnblogs.com/wwph/p/13799984.html
Copyright © 2011-2022 走看看