摩卡it
Mocha是功能丰富JavaScript测试框架,可在 Node.js 和浏览器中运行。
入门
npm install --save-dev mocha
让我们创建一个名为test.js
的文件。
const 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('Array' , function () { // suite
describe( '#indexOf()' , function () { // suite
it( 'should not return -1 when the value is present' , function () { // test
assert.notEqual( -1 , [ 1 , 2 , 3 ].indexOf( 3 ));
});
it( 'should return -1 when the value is not present' , function () { // test
assert.equal( -1 , [ 1 , 2 , 3 ].indexOf( 5 ));
assert.equal( -1 , [ 1 , 2 , 3 ].indexOf( 0 ));
});
});
});
跳入异步风暴!
// it uses `done`, just call it after you think your async will be finished
describe( 'SetTimeOut' , function () {
it( 'why everyone is scared of me' , function ( done ) {
setTimeout( function () {
assert.equal( 1 , 1 );
done();
}, 3000 );
// here timeout might give error, since the default timeout is 2 sec
// though good news is you can alter it yourself using
// flag --timeout 13000 or
// programatically - this.timeout(13000)
});
});
延迟根套件!
setTimeout(function () {
describe( 'master of all suites' , function () {
// write your cases here ..
});
run();
// again use flag --delay to use `run` function.
}, 3000 );
console .log( 'Timer begins for 3 seconds atleast' );
钩子
describe('mocha hooks' , function () {
before( 'description here' , function () {
// runs before all test in this block
});
after( 'description here' , function () {
// runs after all test in this block
});
beforeEach( 'description here' , function () {
// runs before each test in this block
});
afterEach( 'description here' , function () {
// runs after each test in this block
});
// your test cases here ..
});
杂耍异步的承诺
// using chai-as-promised
// bad
doSomethingAsync().then( function ( result ) {
result.should.equal( 'foo' )
done();
}, function ( err ) {
done(err);
});
// good
return doSomethingAsync().should.eventually.equal( 'foo' );
describe( 'Promises' , function () {
it( 'deal with promises' , function () {
// (2+2).should.equal(4)
// or
return Promise .resolve( 2 + 2 ).should.eventually.equal( 4 );
});
});
动态生成测试套件
// adds only two numbers
function add () {
return arguments [ 0 ] + arguments [ 1 ];
}
describe( 'add()' , function () {
var tests = [{
args : [ 1 , 21 ],
expected : 22
}, {
args : [ 11 , 3 ],
expected : 14
}, {
args : [ 3 , 24 ],
expected : 27
}];
tests.forEach( function ( test ) {
it( 'correctly adds ' + test.args.length + ' args' , function () {
var res = add.apply( null , test.args);
assert.equal(res, test.expected);
});
});
});
在此处结帐更多。
翻译自: https://hackernoon.com/introduction-to-mocha-testing-framework-y03q3wq1
摩卡it