学习笔记-js单元测试

单元测试(模块测试)是开发者编写的一小段代码,用于检验被测代码的一个很小的、很明确的功能是否正确。通常而言,一个单元测试是用于判断某个特定条件(或者场景)下某个特定函数的行为。单元测试的目标一般是公共函数库,由程序员自己完成测试。

mocha 测试框架与断言模块

mocha 是一个测试框架,自己已经提供了一套断言,但是,我们通常会需要使用类似 Jasmine 风格的断言,通过 chai 这个断言库,可以提供 expect 风格的断言支持。所以,我们需要安装这两个库。

安装

npm install mocha -g

使用示例

var assert = require('assert');
describe('Array', function() {
  describe('#indexOf()', function() {
    it('should return -1 when the value is not present', function() {
      assert.equal([1,2,3].indexOf(4), -1);
    });
  });
});

describe相当于一个测试栗子?,it相当于一个例子中的一种需要测试到情况

钩子函数

mocha提供4种钩子函数:before()、after()、beforeEach()、afterEach(),这些钩子函数可以用来在用例集/用例函数开始执行之前/结束执行之后,进行一些环境准备或者环境清理的工作。

describe('hooks', function() {

  before(function() {
    // runs before all tests in this block
  });

  after(function() {
    // runs after all tests in this block
  });

  beforeEach(function() {
    // runs before each test in this block
  });

  afterEach(function() {
    // runs after each test in this block
  });

  // test cases
});

钩子函数例子?

  describe('should able to trigger an event', function () {
    var ele
    before(function () {
      ele = document.createElement('button')
      document.body.appendChild(ele)
    })

    it('should able trigger an event', function (done) {
      $(ele).on('click', function () {
        done()
      }).trigger('click')
    })

    after(function () {
      document.body.removeChild(ele)
      ele = null
    })
  })

异步代码测试

定义异步函数

var Ajax = {
    load: function ( url, callback ) {
        callback.call( this, url );
    }
};

module.exports = Ajax;

测试调用

var should = require( 'should' );
var Ajax   = require( '../../src/chapter1/Ajax' );

// 描述 'Ajax' 的行为
describe( 'Ajax', function () {

    // 描述 'Ajax.load()' 方法的行为.
    describe( '#load()', function () {

        // 加载成功后执行回调函数, 获取结果.
        it( 'should return the load result.', function ( done ) {
            Ajax.load( 'url', function ( result ) {
                result.should.equal( 'url' );
                done();
            } );
        } );
    } )
} );


Mocha.js 能够很轻松的实现异步方法的测试,我们只需要在 it 方法中加上 done 形参即可。上述代码中行定义了形式参数 done ,Mocha.js 将会检测是否定义了形参,如果定义了形参,则将会等待形参调用。

断言模块

mocha支持任何可以抛出一个错误的断言模块。例如:should.js、better-assert、expect.js、unexpected、chai等

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值