[Node.js] Testing ES6 Promises in Node.js using Mocha and Chai
2023-09-14 08:59:19 时间
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'); }) });
相关文章
- es6-Set与Map
- JS框架_(JQbar.js)柱状图动态百分比进度条特效
- JS框架_(JQuery.js)图片相册掀开切换效果
- Sublime Es6教程2-基本语法
- 6周学习计划,攻克JavaScript难关(React/Redux/ES6 etc.)
- [WASM] Run WebAssembly in Node.js using the node-loader
- [Node.js] Using ES6 and beyond with Node.js
- [ES6] 19. for ... of
- js es6 Proxy
- js es6 map weakmap
- Node.js 中使用 ES6 中的 import / export 的方法大全
- Atitit js es5 es6新特性 attilax总结
- JS数组对象排序(es6)
- Vue3学习笔记(三)——模板语法、Class 与 Style 、ES6新增数组方法、UI库介绍
- JS与ES6高级编程学习笔记(二)——函数与作用域
- 001-es6变量声明、解构赋值、解构赋值主要用途
- 【JS高级】ES6_模板字符串、let的简谈与应用_12
- 【JS高级】js面向对象三大特性之多态_07
- 【JS高级】js之正则相关函数以及正则对象_02