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

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Node.js] Testing ES6 Promises in Node.js using Mocha and Chai相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

如何欺骗 Node.js 将 .js 文件加载为 ES6 模块?

如何在 Node.js 中使用 ES6 导入? [复制]

node.js中的ES6变量导入名称?

Node.js 的 commonJS 规范 ES6 导入 js 文件

Node.js 的 commonJS 规范 ES6 导入 js 文件

实战ES6 + Node.js 4.x + Express4.x经验分享