• 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)


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

  • 相关阅读:
    js正则表达式常见规则整理
    struts2标签 遍历map集合
    RabbitMQ面试问题
    vue基础学习
    flowableの历史查询
    flowableの日志打印
    flowableのID生成器
    flowableの流程发起人
    SpringBoot+Dubbo(XML配置方式)
    linux安装zookeeper伪分布式
  • 原文地址:https://www.cnblogs.com/wwph/p/13799984.html
Copyright © 2020-2023  润新知