"Mocha.js 101" synchronous, asynchronous and Promise

Source: Internet
Author: User

Previously summary

In the previous article, "Mocha.js 101" Mocha Getting Started, we mentioned how to use mocha.js for front-end automated testing, and made a few simple examples to experience the convenience that Mocha.js brings to us.

In this article, we will learn about synchronous/asynchronous testing of mocha.js and how to test Promise.

Synchronous Code Testing

In the previous article, we've actually learned how to test the synchronization code. Today, we have a BDD style to write a test:

var should     = require (' should '); var Calculator = require (' ... /.. /src/chapter0/calculator ');//describes the behavior of Calculator describe (' Calculator ', function () {    //describes the behavior    of the Calculator.add method Describe (' #add ', function () {        //1 + 2 = 3 behavior of        it (' 1 + 2 = 3 ', function () {            calculator.add (1, 2). should. Equal (3);        } );        2-1 = 1 behavior of        it (' 2-1 = 1 ', function () {            Calculator.minus (2, 1). should.equal (1);        });    }) ;

In the previous article, we've covered common assertion libraries, and should.js is one of them. In the code above, a BDD-style assertion is implemented using Should.js.

Next, we perform the tests:

$ Mocha Test/chapter1/synchronous.js

We will see the following output:

  Calculator    #add      ? 1 + 2 = 3      ? 2-1 = 1  2 passing (9MS)
Asynchronous code (callback) test

When you say JavaScript, you must have a callback function. From the front-end Ajax communication to node. JS asynchronous data access, the callback function runs through the entire JavaScript life cycle.

So how do we test the callback method? First, we first write a class of simulation business logic. Create a src/chapter1/ajax.js and fill in some pile codes:

var Ajax = {    load:function (URL, callback) {        callback.call (this, URL);}    }; Module.exports = Ajax;

The code above simulates an Ajax asynchronous invocation. Call the load function, the incoming request URL, and the success callback function to simulate an Ajax asynchronous request.

Next, we'll write a test for the code above. Mocha.js can easily test the asynchronous method, we just need to add the done parameter to the it method .

We create the Test/chapter1/asynchronous.js file and add the test code:

var should = require (' should '); var Ajax   = require ('. /.. /src/chapter1/ajax '),//describes the behavior of ' Ajax ' describe (' Ajax ', function () {    //description ' Ajax.load () ' method.    Describe (' #load () ', function () {        ////load succeeds after executing the callback function to get the result.        It (' should return the load result. ', function (done) {            ajax.load (' url ', function (result) {                Result.should.eq UAL (' url ');                Done ();            } );        } );    } )} );

The Code 11 line defines the formal parameter done , Mocha.js will detect if the formal parameter is defined, and if the formal parameter is defined, it will wait for the parameter call.

The code 14 line invokes done (), which means that the test execution succeeds and the mocha.js will output a successful result.

Below, we perform this test to see:

Mocha Test/chapter1/asynchronous.js

You will get the following output:

  Ajax    #load ()      should return the load result.  1 Passing (9MS)
Promise Test

Thanks to the introduction of ES 2015, Promise became an integral part of the framework. The advent of Promise makes the nested callback function even more orderly, carrying the new banner of asynchronous processing for JavaScript. (This article does not mainly introduce Promise, so the relevant content can go to see the Reading extension section)

Just like a callback function test, Mocha.js's support for Promise testing is simple: just return a Promise object.

Again, let's start by creating business logic code:

var DB = {    Save:function (object) {        return new Promise (function (resolve, reject) {            resolve ();        });    }}; Module.exports = DB;

The above code simulates the database operation, and in the Save method, returns a Promise to implement the asynchronous storage.

Next, we create the Test/chapter1/promise.js file to write the test code:

var should = require (' should '); var DB     = require ('.. /.. /src/chapter1/db '),//describes the behavior of ' db ' describe (' db ', function () {    //description ' Db.save () ' method.    Describe (' #save () ', function () {        ////  Save successful Promise.then        it (' Save without error. ', function () {            re Turn db.save (' Test ');        } );    } )} );

12 rows return the Promise object returned by the Save method directly to Mocha.js. Mocha.js will determine whether the test was successful based on the results of Promise.

If Promise resolve:

  DB    #save ()      ? Save without error.  1 Passing (8ms)

If Promise reject:

  DB    #save ()      1) Save without error.  0 passing (10ms)  1 failing  1) DB #save () Save without error.:     Error:promise rejected with no or falsy reason
Summarize

This article describes the test methods for Mocha.js synchronous, asynchronous, and Promise. Mocha.js is a very good framework, its support for callback functions, Promise, allows us to easily implement automated testing of asynchronous code.

In the next article, we will introduce the Hooks (hook) of mocha.js, and welcome you to continue to pay attention to

In this paper, the CC BY-NC-SA 3.0 CN Protocol is shared, reproduced, shared and two times the creation of the original source and link, please do not use for commercial purposes.

This article link: http://litecodes.com/dev/frontend/mocha-101-sync-async-and-promise/

"Mocha.js 101" synchronous, asynchronous and Promise

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.