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