码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2016-11-11 23:14:21      阅读:266      评论:0      收藏:0      [点我收藏+]

标签:esc   mod   eating   return   des   through   test   out   ror   

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

 

Install:

npm i -g mocha
npm i -D chai chai-as-promised

 

Index.js

exports.foo = (opts) => {
    return new Promise(
        (resolve, reject) => {
            if(opts === 1) {
                reject(Found an error);
            } else {
                setTimeout( () => {
                    console.log(opts);
                    resolve(opts);
                }, 500);
            }
        }
    );
};

exports.foo(2)
.catch(err => {
    console.log(err);
});

 

test/index.js:

const chai = require(chai);
const expect = chai.expect;
const chaiAsPromised = require(chai-as-promised);

const index = require(../index.js);

chai.use(chaiAsPromised);

describe(Function foo, () => {
    it(should accpet anything but one, () => {
        const promise = index.foo(0);
        return expect(promise).to.eventually.equal(0);
    });

    it(should throw error is apply one, () => {
        const promise = index.foo(1);
       // return expect(promise).to.be.rejected;
        return expect(promise).to.be.rejectedWith(Found an error);
    })
});

 

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

标签:esc   mod   eating   return   des   through   test   out   ror   

原文地址:http://www.cnblogs.com/Answer1215/p/6055610.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!