Detailed introduction to the installation and use of the NodeJs testing framework Mocha

Source: Internet
Author: User
This article describes how to use Mocha to get started with ease. If you do not know anything about the test before, this article can also be used as an entry to JavaScript unit testing. This article describes how to use Mocha to get started with ease. If you do not know anything about the test before, this article can also be used as a # wiki/48.html "target =" _ blank "> JavaScript unit test entry.

Mocha is a Javascript unit test framework running in nodejs and a browser. It is quite easy to use and use. In fact, the unit test framework is similar to each other and basically includes the following content:

Macro, attribute, or function used to write Test Cases
Determines whether the database can pass
Auxiliary libraries, such as the hook Library (calling some functions or methods before and after testing), and exception checks (some functions throw exceptions when some parameters are involved ), input Combination (supports multiple input combinations of parameters.
Support IDE Integration
The following is a concise description of the order in the official documents.

Installation and preliminary use

Run the following commands in the console:

$ npm install -g mocha$ mkdir test$ $EDITOR test/test.js

You can write the following code:

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

Return to the console:

$  mocha  .   1 test complete (1ms)

Here, mocha searches for the content in the test folder under the current file directory and runs it automatically.

Database Determination

This is to determine whether the test case passes. By default, the assert library of nodejs can be used. At the same time, Mocha allows us to use different judgment libraries. Now we can support the following judgment libraries, there are some differences in the usage of each database. You can refer to the relevant documentation.

1 shoshould. js BDD style shown throughout these docs (BDD mode, this document uses this judgment Library)
2 better-assert) c-style self-documenting assert () (judgment database under C-Model)
3 reverse CT. js reverse CT () style assertions (Judge database of reverse CT Mode)
4 unexpected the extensible BDD assertion toolkit
5 chai shortct (), assert () and shocould style assertions

Code Synchronization

The synchronization code indicates that the synchronization function is tested. The above Array-related example code is. This is easy to understand.

Asynchronous code

Only asynchronous code tests are performed. The reason is that many asynchronous functions are used in nodejs. In the following code, this test case is completed only after the done () function is executed.

Describe ('user', function () {describe ('# save ()', function () {it ('could save without error', function (done) {var user = new User ('luna '); user. saveAsync (function (err) {if (err) throw err; done (); // This test case is complete only after this function is executed. });});});});

Describe and it

The above instance code is relatively simple, so what is describe and it? In general, we can see that describe should declare a TestSuit (Test Set), and the test set can be nested and managed, while the it Declaration defines a specific test case. Take the bdd interface as an example. The specific source code is as follows:

  /**     * Describe a "suite" with the given `title`     * and callback `fn` containing nested suites     * and/or tests.     */    context.describe = context.context = function(title, fn) {      var suite = Suite.create(suites[0], title);      suite.file = file;      suites.unshift(suite);      fn.call(suite);      suites.shift();      return suite;    };      /**     * Describe a specification or test-case     * with the given `title` and callback `fn`     * acting as a thunk.     */    context.it = context.specify = function(title, fn) {      var suite = suites[0];      if (suite.pending) {        fn = null;      }      var test = new Test(title, fn);      test.file = file;      suite.addTest(test);      return test;    };

Hooks (Hook)

In fact, this is a very common function in writing unit test, that is, a callback function (Hook) is required before or after the test case and test case set ). Mocha provides before (), after (), beforeEach (), and aftetEach (). The sample code is as follows:

Describe ('hooks', function () {before (function () {// runs before all tests in this block // The function will be called once before all test cases are executed}); after (function () {// runs after all tests in this block // The function will be called once after all test cases are executed}); beforeEach (function () {// runs before each test in this block // The function will be called once before each test case is executed}); afterEach (function () {// runs after each test in this block // The function will be called once after each test case is executed}); // test cases });

Hooks has the following usage:

Describing Hooks-you can add descriptions to hook functions to better view problems
Asynchronous Hooks (Asynchronous hook): the hook function can be synchronous or Asynchronous. As for the test case, the following is the sample code of Asynchronous HOOK:

BeforeEach (function (done) {// asynchronous function db. clear (function (err) {if (err) return done (err); db. save ([tobi, loki, jane], done );});});

Root-Level Hooks (Global hook) is executed outside describe (outside the test case set), which is generally executed before or after all test cases.
Pending Tests (Pending test)

There are some tests that haven't been completed yet, a bit similar to TODO, the following code:

Describe ('array', function () {describe ('# indexOf ()', function () {// pending test below does not write the callback function it ('could return-1 when the value is not present ');});});

Exclusive Tests (test it)

Test is to allow a test set or test case. Only one of them is executed and all others are skipped. See the following test case set:

Describe ('array', function () {describe. only ('# indexOf ()', function (){//...}); // The test set will not be executed describe ('# ingored ()', function (){//...});});

The following is a test case:

Describe ('array', function () {describe ('# indexOf ()', function () {it. only ('could return-1 unless present', function (){//...}); // the test case will not execute it ('could return the index when present', function (){//...});});});

It should be noted that Hooks (callback function) will be executed.

Comprehensive Tests (including Tests)

In contrast to the only function, the skip function will allow the mocha system to ignore the current test case set or test case. All test cases with skip will be reported as Pending.
The following is the sample code for the set of test cases:

Describe ('array', function () {// This test routine will be describe lost by ingore. skip ('# indexOf ()', function (){//...}); // This test will be executed describe ('# indexOf ()', function (){//...});});

The following example shows a specific test case:

Describe ('array', function () {describe ('# indexOf ()', function () {// The testing routine is replaced by ingore. skip ('could return-1 unless present', function (){//...}); // it ('could return the index when present', function (){//...});});});

Dynamically Generating Tests (Dynamically generate Test Cases)

In fact, this is also available in many other test tools, such as NUnit, that is, replacing the parameters of the test case with a set to generate different test cases. The following is an example:

Var assert = require ('assert '); function add () {return Array. prototype. slice. call (arguments ). reduce (function (prev, curr) {return prev + curr ;}, 0) ;}describe ('add () ', function () {var tests = [{args: [1, 2], expected: 3}, {args: [1, 2, 3], expected: 6}, {args: [1, 2, 3, 4], expected: 10}]; // The following will generate three different test cases, which is equivalent to writing three it function test cases. Tests. forEach (function (test) {it ('correctly adds '+ test. args. length + 'args', function () {var res = add. apply (null, test. args); assert. equal (res, test. expected );});});});

Interfaces (Interface)

Mocha's interface system allows users to write their test case sets and specific test cases with different styles of functions or styles. mocha Has BDD, TDD, Exports, QUnit and Require styles.

BDD-this is the default mocha style. The sample code in this article is in this format.
It provides describe (), context (), it (), before (), after (), beforeEach (), and afterEach () functions. The sample code is as follows:

describe('Array', function() {    before(function() {      // ...    });    describe('#indexOf()', function() {      context('when not present', function() {        it('should not throw an error', function() {          (function() {            [1,2,3].indexOf(4);          }).should.not.throw();        });        it('should return -1', function() {          [1,2,3].indexOf(4).should.equal(-1);        });      });      context('when present', function() {        it('should return the index where the element first appears in the array', function() {          [1,2,3].indexOf(3).should.equal(2);        });      });    });  });

TDD-provides functions for suite (), test (), suiteSetup (), suiteTeardown (), setup (), and teardown, in fact, similar to the BDD interface (suite is equivalent to describe and test is equivalent to it), the sample code is as follows:

suite('Array', function() {  setup(function() {    // ...  });  suite('#indexOf()', function() {    test('should return -1 when not present', function() {       assert.equal(-1, [1,2,3].indexOf(4));    });  });});

The Exports-object values are all set of test cases, and the function values are all test cases. The keywords before, after, beforeEach, and afterEach must be defined.
The sample code is as follows:

module.exports = {  before: function() {    // ...  },  'Array': {    '#indexOf()': {      'should return -1 when not present': function() {        [1,2,3].indexOf(4).should.equal(-1);      }    }  }};

QUnit-similar to TDD, using suit and test functions also includes before (), after (), beforeEach () and afterEach (), but the usage is slightly different, refer to the following code:

function ok(expr, msg) {  if (!expr) throw new Error(msg);}suite('Array');test('#length', function() {  var arr = [1,2,3];  ok(arr.length == 3);});test('#indexOf()', function() {  var arr = [1,2,3];  ok(arr.indexOf(1) == 0);  ok(arr.indexOf(2) == 1);  ok(arr.indexOf(3) == 2);});suite('String');test('#length', function() {  ok('foo'.length == 3);});

Require-this interface allows us to use the require keyword to re-encapsulate keywords such as describe and it, so as to avoid global variables.
Run the following code:

Var testCase = require ('mocha '). describe; var pre = require ('mocha '). before; var assertions = require ('mocha '). it; var assert = require ('assert '); testCase ('array', function () {pre (function (){//...}); testCase ('# indexOf ()', function () {assertions ('could return-1 when not present', function () {assert. equal ([1, 2, 3]. indexOf (4),-1) ;}) ;};}); The above default Interface is BDD. if you want

The above default Interface is BDD. To use other interfaces, you can use the following command line:

Mocha-ui interface (TDD | Exports | QUnit ...)

Reporters (Test Report/result style)

Mocha supports testing results of different formats. Currently, it supports Spec, Dot Matrix, Nyan, TAP... The default style is Spec. If other styles are needed, use the following command line:

Mocha -- reporter specific style (Dot Matrix | TAP | Nyan ...)

Editor Plugins

Mocha can be well integrated into TextMate, Wallaby. js, and JetBrains (IntelliJ IDEA, WebStorm). Here we use WebStorm as an example. JetBrains provides NodeJS plugin so that we can use mocha and nodeJs well. Add mocha related menus,

Here we can run it directly in WebStorm to debug the mocha test case.

The preceding section describes how to install and use the NodeJs testing framework Mocha. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.