JavaScript Unit Test Framework: Mocha Vs Qunit

 

Mocha VS Qunit

 

Assess Category

Assess Items

MochaQunit
Setup
  
 
Installation

Require to install node.js and Mocha.js

$ npm install mocha.js

Don't need install
Dependency ManagementManual handleManual handle
Support AMDSupport AMD/No-AMD styleSupport AMD/No-AMD style
Support test jQuery's featuresNeed to import mocha.js, mocha.css and mocha.setup('bdd'), mocha.run();in the htmlNeed to import qunit.js, qunit.css
Support server-side JavaScript

Run the test in command directly,

so more fast

Run the test in browser,not frequently-used
Test Structure 


 
Test Case Organization

Support modules nested

describe(' ',function(){

describe(' ',function(){

});

});

Don't support modules nested

Qunit.module(' ', function(){

} );

Support async testUse function done()

Use function async()

ReadabilityUse describe,itUse module, test
Work with Sinon.jsRequire to install sinon.jsimport sinon.js
AssertionRequire to install chai.js or expect.jsNo need to install other assertion library
Test Case Execution

1 .Use Timeouts function set a test/tests pass or not

2.Use skip(),only() to run or not run a test/tests

Use skip(),only() to run or not run a test/tests

ReportsTest Result ReportSimple,don't display assertion result of each caseBetter appreciation,display assertion result of each case
Test Coverage Report Use istanbul to create coverage report
Integration and configurationIntegrate with Grunt

Install grunt-mocha

set some configuration in Gruntfiles.js

Install grunt-qunit-junit

Install grunt-qunit-istanbul

set some configuration in Gruntfiles.js

Compare

Install

Mocha need to install but Qunit needn't.

Mocha:

    • install node.js(Download::https://nodejs.org/en/)
    • install mocha
    • global install: $ npm install --global mocha
    • Install in your development project
    • :Cd to your project directory : 
    • $ npm install mocha

 Qunit:
       Import qunit.js

Test Grammar 

  Mocha has difference interfaces so it has more test style,BDD, TDD, QUnit, Export and Require-style.

  1. BDD

    The BDD interface provides describe(), context(), it(), specify(), before(), after(), beforeEach(), and afterEach().
    context() is just an alias for describe(), and behaves the same way; it just provides a way to keep tests easier to read and organized. Similarly, specify() is an alias for it().

    describe('Array', function() {

           it(' ', function(){

           });

      });

  2. TDD

    The  TDD interface provides suite(), test(), suiteSetup(), suiteTeardown(), setup(), and teardown():
     
    suite('#indexOf()', function() {
    test('should return -1 when not present', function() {
               assert.equal(-1, [1,2,3].indexOf(4));
          });
      });
  3. Qunit

    The QUnit-inspired interface matches the “flat” look of QUnit, where the test suite title is simply defined before the test-cases. Like TDD, it uses suite() and test(), but resembling BDD, it also contains before(), after(), beforeEach(), and afterEach(). 

    suite('Array');
    test('#length', function() {
                var arr = [1,2,3];
                ok(arr.length == 3);
          }
  4. Exports

The Exports interface is much like Mocha’s predecessor expresso. The keys before, after, beforeEach, and afterEach are special-cased, object values are suites, and function values are test-cases:

module.exports = {
      'Array': {
           '#indexOf()': {
                 'should return -1 when not present':  function() {
                       [1,2,3].indexOf(4).should.equal(-1);
                  }
            }
      };
    };
 
   Qunit is not so flexible only use Qunit.module()  and Qunit.test()

Assertion

Mocha: According to different require mocha could install different assertion, like chai.js, shoud.js, expect.js, best-assert,…

Mocha allows you to use any assertion library you wish,  we’re using Node.js’ built-in it. you can use libraries such as:

  1. should.js - BDD style shown throughout these docs

     Click here to expand...
    $ npm install should
    var should = require('should');
    (5). should.be.exactly(5). and.be.a.Number();
    var should = require('should/as-function');
    should(10).be.exactly(5). and.be.a.Number()
  2. expect.js expect() style assertions

     Click here to expand...
    $ npm install chai.js
    var expect = require('expect.js');
    ok
    expect(). to.be.ok();
    expect(). to.not.be.ok();
    be/equal
    expect(). to.be();
  3. chai - expect()assert() and should-style assertions

     Click here to expand...
    $ npm install chai
    var chai = require('chai')
    , expect = chai.expect
    , should = chai.should();
    , assert = chai.assert;
    Var foo = 'bar';
    assert.equal(foo, 'bar', 'foo equal bar');
    expect(foo).to.equal('bar');
    foo.should.equal('bar');
  4. better-assert - C-style self-documenting assert()
  5. unexpected - “the extensible BDD assertion toolkit”

Qunit use itself assert

          - ok(state, message) 
          - equal(actual, expected, message) 
          - notEqual (actual, expected, message) 
          - deepEqual (actual, expected, message) 
          - notDeepEqual(actual, expected, message) 
          - strictEqual (actual, expected, message) 
          - notStrictEqual(actual, expected, message) 

Report  

Mocha: The browse report of mocha test is relative simple and not so beautiful.

Qunit test report is relative more beautiful and clear, we could through the select box run the test case which we want. Another, the report will list all the assert of each case.

Asynchronous code

Testing asynchronous code with Mocha could not be simpler! Simply invoke the callback when your test is complete. By adding a callback (usually named done) to it(), Mocha will know that it should wait for this function to be called to complete the test.

describe('User', function() { describe('#save()', function() { it('should save without error', function(done) { var user = new User('Luna'); user.save(done); }); }); });

Qunit use async to wait for asynchronous operation and it often use with setTimeout function.

QUnit.test( "assert.async() test", function( assert ) {
var done = assert.async();
var input = $( "#test-input" ).focus();
setTimeout(function() {
assert.equal( document.activeElement, input[0], "Input was focused" );
done();
});
});

Test jQuery's features

Mocha: Run mocha test in browse need set below

    1. Create test folder

    2. $ mocha init test

       Will create four file:index.html, test.js, mocha.js and mocha.css

       The index.html will include:
       
     3. Import the files which we needs like the tested js, the dependence,etc.

Qunit: Just need to import qunit.js, qunit.css, the tested js file and other dependence.

Test server-side JavaScript

Mocha: No need browse and could run the test with command and run very fast, $ npm test

Qunit: Run test with browse, so need more time.

Test control

Mocha could use the Timeouts function to control a test case run time and if the time out of the time,it will failed.But qunit don't have this function.

describe('a suite of tests', function() {
      this.timeout(500);
      it('should take less than 500ms', function (done) {
            //if the case take more than 500ms it will fail
       });
});

Qunit don't have this function.

Integrate with Grunt

Mocha:grunt-mocha: To run mocha test in grunt; grunt-mocha-istanbul: To code coverage for JavaScript Code.

Gruntfile.js

  grunt.initConfig({

       pkg: pkgJson,

             mocha:{

              test:{
  src:['<%= pkg.projectFiles.mochaTests %>']
  }
  },
      grunt.loadNpmTasks('grunt-mocha');
      grunt.registerTask('test', mocha);
  }

Qunit: grunt-qunit-junit: To run qunit test in grunt; grunt-qunit-istanbul: To code coverage for JavaScript Code.

Gruntfile.js

grunt.initConfig({

        pkg: pkgJson,
qunit_junit: {
options: {
dest: qunitJunitReportPath
  }
},
qunit: {
options: {
console: false,
timeout: 10000,
coverage: {
disposeCollector: true,
src: '<%= pkg.projectFiles.javascript %>',
htmlReport: qunitHtmlReportPath,
coberturaReport: qunitCoberturaReportPath,
cloverReport: qunitCloverReportPath,
jsonSummaryReport: qunitJsonSummaryReportPath,
instrumentedFiles: tempPath,
reportOnFail: true,
coverageTempPath: coverageTempPath,
linesThresholdPct: '<%= pkg.coverageThreshold %>',
branchesThresholdPct: '<%= pkg.branchCoverageThreshold %>'
 }
},
all: '<%= pkg.projectFiles.qunitTests %>'
 }

            grunt.loadNpmTasks('grunt-qunit-istanbul');

      grunt.loadNpmTasks('grunt-qunit-junit');

}

Summary

Mocha test server-side common and run with command, so it faster

Qunit test ui more common and need less dependence and plug-in.

For reservation js is tendency ui and the two frame run broswer test has no obvious difference of speed, another our framework has complete configuration of Qunit,

so I support to use  Qunit to test our javascript.  

What is mocha?

Mocha is a feature-rich JavaScript test framework running on Node.js(:https://nodejs.org/en/) and in the browser, making asynchronous testing simple and fun. Mocha tests run serially, allowing for flexible and accurate reporting, while mapping uncaught exceptions to the correct test cases. Detail:https://mochajs.org

Feature

- Open Source Framework 
- Started in Node 
- Supports both client-side and server-side testing 
- Supports both BDD and TDD style tests 
- Supports both command line and browser 
- Supports any JavaScript assertion library (YUI Port, expect.js, should.js, jshould.js, assert.js, chai.js) 
- Supports asynchronous testing 
- Requires an assertion library

What is QUnit? 

A JavaScript Unit Testing framework. QUnit is a powerful, easy-to-use JavaScript unit testing framework. It's used by the jQuery, jQuery UI and jQuery Mobile projects and is capable of testing any generic JavaScript code.Detail:http://qunitjs.com/ 

Feature 

- Similar to server-side frameworks(JUnit, Nunit)
- Built by the jQuery team
- Used to test jQuery's features
- No dependencies
- Can test server-side JavaScript

 

 

转载于:https://www.cnblogs.com/lj8023wh/p/6674621.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值