测试框架Mocha与断言expect

标签:not   应该   测试的   指定   empty   var   hello   项目   写代码   

原文地址:http://www.cnblogs.com/lqcdsns/p/6237775.html

测试框架Mocha与断言expect
在浏览器和Node环境都可以使用
除了Mocha以外,类似的测试框架还有Jasmine、Karma、Tape等,也很值得学习。

整个项目源代码:

为什么学习测试代码?
1. react的开发不适合网页端的调试和测试
2. 把关所写代码质量,防止bug和漏洞

要测试的文件add.js
测试文件命名为:add.test.js或者add.spec.js

测试脚本可以独立运行。
测试脚本里包含一个或多个describe块,每个describe块应该包括一个或多个it块

add.test.js:

var add = require(‘./add.js‘);
var expect = require(‘chai‘).expect; // 引入断言库,引入的断言库是chai,并且指定使用它的expect风格

describe(‘加法的测试‘, function () {
it(‘1 + 1应该等于2‘, function () {
expect(add(1, 1).to.be.equal(2)); // 断言
});
});

断言: 判断源码的执行结果与预期是否一致,如果不一致就抛出一个错误
所有的测试用例(it块)都应该含有一句或多句的断言。

// 执行测试脚本
mocha add.test.js

expect断言例子:
// 相等或不相等
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/);

 


// mocha测试多个脚本
mocha file1.test.js file2.test.js file3.test.js

Mocha默认运行test子目录里面的测试脚本。
所以,一般都会把测试脚本放在test目录里面,然后执行mocha测试代码
// 执行默认test里的测试脚本
mocha

猜你喜欢

转载自blog.csdn.net/qq_38995031/article/details/80608415