[node. js] Testing ES6 Promises in node. js using Mocha and Chai

Source: Internet
Author: User

Writing great ES6 style Promises for node. JS is only half the battle. Your great modules must include tests as well to ensure the future iterations don ' t break them. In this lesson, I show you a simple ES6 Promise in node. js, then walk to through creating tests in Mocha using Chai and C hai-as-promised to test both resolve and reject methods.

Install:

NPM i-D Chai chai-as-promised

Index.js

Exports.foo = (opts) = = {    return NewPromise (Resolve, Reject)= {            if(opts = = =1) {Reject ('Found An error'); } Else{setTimeout ()={Console.log (opts);                Resolve (opts); },  -); }        }    );}; Exports.foo (2).Catch(Err ={console.log (err);});

Test/index.js:

ConstChai = require ('Chai');ConstExpect =Chai.expect;Constchaiaspromised = require ('chai-as-promised');Constindex = require ('.. /index.js'); Chai.use (chaiaspromised);d Escribe ('Function Foo', () ={It ('should accpet anything but one', () = {        ConstPromise = Index.foo (0); returnExpect (promise). To.eventually.equal (0);    }); It ('should throw error is apply one', () = {        ConstPromise = Index.foo (1); //return expect (promise). to.be.rejected;        returnExpect (promise). To.be.rejectedWith ('Found An error'); })});

[node. js] Testing ES6 Promises in node. js using Mocha and Chai

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.