mocha单元测试

我是开发为什么要写单元测试呢

  1. 逼格高啊,没有单元测试的代码在github上是会被鄙视的
  2. 可以通过测试用例更快更好的理解代码
  3. 祖传代码 不敢改,改了这个功能,那个就不好使了
    举个栗子:张老师接到一个任务,做了几个功能后交给了宋同学,宋同学不知道有这几个方法,继续完成新的功能,可能把以前张老师已经完成的改的很乱,到上线才发现原来的功能没有了,这个锅怎么背 哈哈
    在这里插入图片描述

mocha测试环境

mocha是一个可以在node和浏览器环境运行的测试框架
mocha官网

安装mocha

npm install mocha -g

测试需要断言函数,mocha自己是没有的,需要用一些断言函数
比较常用的有assert,shouldjs,chai

简单的测试用例

语法 assert.equal(actual,expected)
actual(实际值), expected( 期望值) 相当于==
如果actual和expected相等的话,测试通过

assert.equal(actual,expected)

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

语法 assert.deepEqual(actual,expected)

判断对象内容是否相等

describe('assert', function() {
  it('a和b应当深度相等', function() {
    var a = {
      c: {
        e: 1
      }
    };
    var b = {
      c: {
        e: 1
      }
    };
    assert.deepEqual(a, b);
  });
});

判断对象的属性

const user = {
    name: 'jsong',
    eat: () => 'apple',
    speak: () => 'say hello',
    net: function () {
    }
}

describe('User', function() {
  describe('users', function() {
    it('user name should == jsong ', function() {
      // user 应该的 name 属性 应该==jsong
      assert.equal(user.name, 'jsong');
    });
    it('user should eat apple', function() {
      // user 的 eat() 方法 应该返回 apple
      assert.equal(user.eat(), 'apple');
    });
    it('user should have name', function() {
      // user 应该有name 属性
      user.should.have.property('name');
    });
  });
});

异步测试

也很简单,只需要在回掉函数中在一个参数就可以了,一般命名为done。mocha自己就知道需要等这个这个函数被调用才完成测试

function UserObj(name) {
  this.name = name
}

UserObj.prototype.save = function () {
  http.get({
    hostname: 'localhost',
    port: 80,
    path: '/'
  }, res => console.log(111))
 
}

describe('asynchronous', function () {
  describe(' save userObj ', function () {
    it('should save without error ', function (done) {
      const user = new UserObj('jsong')
      user.save(function (err) {
        if (err) done(err);
        else done();
      })
      // done()
      // user.save(done)
    })
  })
})

钩子函数

mocha提供了before(),beforeEach(),after(),afterEach() 帮助我们设置前提条件,和测试后的清理。

describe('hooks', function () {
  it('my test', () => {
    // this.timeoute(1000)
    assert.ok(true)
  })
  before(function () {
    console.log('before')
  })

  after(function () {
    console.log('after')
  })

  beforeEach(function () {
    console.log('beforeEach')
  })

  after(function () {
    console.log('after')
  })

  afterEach(function () {
    console.log('after')
  })
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值