PHPStorm中如何对nodejs项目进行单元测试详解


Posted in NodeJs onFebruary 28, 2019

安装必要的包

nodejs的单元测试最常用的是使用mocha包。首先确保你本地安装nodejs,之后按照mocha包。

npm install mocha -g

然后还需要安装相关的断言工具,Node.js中常用的断言库有:

  • assert: TDD风格
  • should: BDD风格
  • expect: BDD风格
  • chai: BDD/TDD风格

使用npm install安装这些断言库其中之一即可。

PHPStorm配置nodejs单元测试环境

在PHPStorm中选择菜单:Run -> Edit Configurations,点击右上角添加mocha。

PHPStorm中如何对nodejs项目进行单元测试详解

分别填写下面几项,关于mocha单元测试可以参考官网:https://mochajs.org/

  • Name: 随便一个运行配置的名称,如MochaTest
  • Working directory: 当前项目目录
  • Mocha package: Mocha安装包的目录,node_modules\mocha
  • User interface: 测试类型,这里选择TDD(对应assert库)
  • Test directory: 这一项可以选择测试目录或文件
    • All in directory: 整个目录都进行测试
    • File patterns: 某种模式的文件,可以填正则表达式
    • Test file: 某个特定的测试文件

填写完成并且没有报错后点击OK。

Nodejs进行单元测试

这里我们选择assert库,TDD模式进行单元测试。在上面选定的Test directory目录下新建一个测试文件test.js.

const assert = require('assert');

// 测试Array类型的方法
suite('Array', function() {
 // 测试 indexOf方法
 suite('#indexOf()', function() {
  // 测试用例
  test('should return -1 when not present', function() {
   assert.equal(-1, [1, 2, 3].indexOf(4));
  });
 });
});

点击选择Mocha运行,在PHPStorm下面的输出框中有测试的结果,绿色表示通过,红色表示失败。

PHPStorm中如何对nodejs项目进行单元测试详解

断言库的使用

mocha进行单元测试的时候,除了能够使用assert断言库,只要断言代码中抛出Error,mocha就可以正常工作。

assert库:TDD风格

下面列举assert库中常用的断言函数,详情可参考官网:https://www.npmjs.com/package/assert

  • assert.fail(actual, expected, message, operator)
  • assert(value, message), assert.ok(value, [message])
  • assert.equal(actual, expected, [message])
  • assert.notEqual(actual, expected, [message])
  • assert.deepEqual(actual, expected, [message])
  • assert.notDeepEqual(actual, expected, [message])
  • assert.strictEqual(actual, expected, [message])
  • assert.notStrictEqual(actual, expected, [message])
  • assert.throws(block, [error], [message])
  • assert.doesNotThrow(block, [message])
  • assert.ifError(value)

其中的参数说明如下:

  • value: 实际值
  • actual: 实际值
  • expected: 期望值
  • block: 语句块
  • message: 附加信息

BDD风格should.js断言库

安装方法:npm install should --save-dev,官网地址:https://github.com/shouldjs/should.js

const should = require('should');

const user = {
 name: 'tj'
 , pets: ['tobi', 'loki', 'jane', 'bandit']
};

user.should.have.property('name', 'tj');
user.should.have.property('pets').with.lengthOf(4);

// If the object was created with Object.create(null)
// then it doesn't inherit `Object.prototype`, so it will not have `.should` getter
// so you can do:
should(user).have.property('name', 'tj');

// also you can test in that way for null's
should(null).not.be.ok();

someAsyncTask(foo, function(err, result){
 should.not.exist(err);
 should.exist(result);
 result.bar.should.equal(foo);
});

should库可以使用链式调用,功能非常强大。相关文档参考:http://shouldjs.github.io/

user.should.be.an.instanceOf(Object).and.have.property('name', 'tj');
user.pets.should.be.instanceof(Array).and.have.lengthOf(4);

常用的should断言方法:

无意义谓词,没作用增加可读性:.an, .of, .a, .and, .be, .have, .with, .is, .which

  • should.equal(actual, expected, [message]): 判断是否相等
  • should.notEqual(actual, expected, [message]): 判断是否不相等
  • should.strictEqual(actual, expected, [message]): 判断是否严格相等
  • should.notStrictEqual(actual, expected, [message]): 判断是否严格不相等
  • should.deepEqual(actual, expected, [message]): 判断是否递归相等
  • should.notDeepEqual(actual, expected, [message]): 判断是否递归不想等
  • should.throws(block, [error], [message]): 判断是否抛出异常
  • should.doesNotThrow(block, [message]): 判断是否不抛出异常
  • should.fail(actual, expected, message, operator): 判断是否不等
  • should.ifError(err): 判断是否为错误
  • should.exist(actual, [message]): 判断对象是否存在
  • should.not.exist(actual, [message]): 判断对象是否不存在

另外should还提供了一系列类型判断断言方法:

// bool类型判断
(true).should.be.true();
false.should.not.be.true();

// 数组是否包含
[ 1, 2, 3].should.containDeep([2, 1]);
[ 1, 2, [ 1, 2, 3 ]].should.containDeep([ 1, [ 3, 1 ]]);

// 数字比较
(10).should.not.be.NaN();
NaN.should.be.NaN();
(0).should.be.belowOrEqual(10);
(0).should.be.belowOrEqual(0);
(10).should.be.aboveOrEqual(0);
(10).should.be.aboveOrEqual(10);

// Promise状态判断
// don't forget to handle async nature
(new Promise(function(resolve, reject) { resolve(10); })).should.be.fulfilled();

// test example with mocha it is possible to return promise
it('is async', () => {
 return new Promise(resolve => resolve(10))
  .should.be.fulfilled();
});

// 对象的属性判断
({ a: 10 }).should.have.property('a');
({ a: 10, b: 20 }).should.have.properties({ b: 20 });
[1, 2].should.have.length(2);
({}).should.be.empty();

// 类型检查
[1, 2, 3].should.is.Array();
({}).should.is.Object();

几种常见的测试风格代码举例

BDD

BDD提供的接口有:describe(), context(), it(), specify(), before(), after(), beforeEach(), and afterEach().

describe('Array', function() {
 before(function() {
  // ...
 });

 describe('#indexOf()', function() {
  context('when not present', function() {
   it('should not throw an error', function() {
    (function() {
     [1, 2, 3].indexOf(4);
    }.should.not.throw());
   });
   it('should return -1', function() {
    [1, 2, 3].indexOf(4).should.equal(-1);
   });
  });
  context('when present', function() {
   it('should return the index where the element first appears in the array', function() {
    [1, 2, 3].indexOf(3).should.equal(2);
   });
  });
 });
});

TDD

提供的接口有: suite(), test(), suiteSetup(), suiteTeardown(), setup(), and teardown():

suite('Array', function() {
 setup(function() {
  // ...
 });

 suite('#indexOf()', function() {
  test('should return -1 when not present', function() {
   assert.equal(-1, [1, 2, 3].indexOf(4));
  });
 });
});

QUNIT

和TDD类似,使用suite()和test()标记测试永烈,包含的接口有:before(), after(), beforeEach(), and afterEach()。

function ok(expr, msg) {
 if (!expr) throw new Error(msg);
}

suite('Array');

test('#length', function() {
 var arr = [1, 2, 3];
 ok(arr.length == 3);
});

test('#indexOf()', function() {
 var arr = [1, 2, 3];
 ok(arr.indexOf(1) == 0);
 ok(arr.indexOf(2) == 1);
 ok(arr.indexOf(3) == 2);
});

suite('String');

test('#length', function() {
 ok('foo'.length == 3);
});

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对三水点靠木的支持。

NodeJs 相关文章推荐
nodejs npm package.json中文文档
Sep 04 NodeJs
ubuntu下安装nodejs以及升级的办法
May 08 NodeJs
详解nodejs中exports和module.exports的区别
Feb 17 NodeJs
NodeJS学习笔记之Module的简介
Mar 24 NodeJs
nodejs爬虫遇到的乱码问题汇总
Apr 07 NodeJs
详解nodejs模板引擎制作
Jun 14 NodeJs
详解IWinter 一个路由转控制器的 Nodejs 库
Nov 15 NodeJs
Nodejs模块的调用操作实例分析
Dec 25 NodeJs
nodejs使用async模块同步执行的方法
Mar 02 NodeJs
Nodejs让异步变成同步的方法
Mar 02 NodeJs
nodejs同步调用获取mysql数据时遇到的大坑
Mar 02 NodeJs
使用nodejs分离html文件里的js和css详解
Apr 12 NodeJs
Nodejs对postgresql基本操作的封装方法
Feb 20 #NodeJs
深入理解nodejs搭建静态服务器(实现命令行)
Feb 05 #NodeJs
Nodejs实现的操作MongoDB数据库功能完整示例
Feb 02 #NodeJs
基于Koa(nodejs框架)对json文件进行增删改查的示例代码
Feb 02 #NodeJs
用Electron写个带界面的nodejs爬虫的实现方法
Jan 29 #NodeJs
NVM安装nodejs的方法实用步骤
Jan 16 #NodeJs
nodeJS进程管理器pm2的使用
Jan 09 #NodeJs
You might like
《PHP边学边教》(02.Apache+PHP环境配置――上篇)
2006/12/13 PHP
浅析PHP水印技术
2007/02/14 PHP
攻克CakePHP系列一 连接MySQL数据库
2008/10/22 PHP
深入解析phpCB批量转换的代码示例
2013/06/27 PHP
tp5(thinkPHP5)框架连接数据库的方法示例
2018/12/24 PHP
laravel按天、按小时,查询数据的实例
2019/10/09 PHP
JS实现图片横向滚动效果示例代码
2013/09/04 Javascript
javascript中字符串的定义示例代码
2013/12/19 Javascript
原生Js实现简易烟花爆炸效果的方法
2015/03/20 Javascript
JS实现控制表格行内容垂直对齐的方法
2015/03/30 Javascript
javascript实现自动填写表单实例简析
2015/12/02 Javascript
jQuery+JSON实现AJAX二级联动实例分析
2015/12/18 Javascript
JavaScript中的this机制
2016/01/30 Javascript
Node.js本地文件操作之文件拷贝与目录遍历的方法
2016/02/16 Javascript
详解AngularJS中的表单验证(推荐)
2016/11/17 Javascript
js实现可输入可选择的select下拉框
2016/12/21 Javascript
jQuery插件HighCharts绘制2D柱状图、折线图和饼图的组合图效果示例【附demo源码下载】
2017/03/09 Javascript
react-native 完整实现登录功能的示例代码
2017/09/11 Javascript
Bootstrap模态对话框用法简单示例
2018/08/31 Javascript
微信小程序缓存支持二次开发封装实现解析
2019/12/16 Javascript
JS实现容器模块左右拖动效果
2020/01/14 Javascript
原生js+canvas实现下雪效果
2020/08/02 Javascript
[01:00:17]DOTA2-DPC中国联赛 正赛 SAG vs Dynasty BO3 第二场 1月25日
2021/03/11 DOTA
用Python和MD5实现网站挂马检测程序
2014/03/13 Python
Python psutil模块简单使用实例
2015/04/28 Python
Python的时间模块datetime详解
2017/04/17 Python
python win32 简单操作方法
2017/05/25 Python
Python实现找出数组中第2大数字的方法示例
2018/03/26 Python
详解python实现数据归一化处理的方式:(0,1)标准化
2019/07/17 Python
python+openCV调用摄像头拍摄和处理图片的实现
2019/08/06 Python
简单了解python调用其他脚本方法实例
2020/03/26 Python
用python按照图像灰度值统计并筛选图片的操作(PIL,shutil,os)
2020/06/04 Python
纯CSS3实现地球自转实现代码(图文教程附送源码)
2012/12/26 HTML / CSS
财务工作个人求职的自我评价
2013/12/19 职场文书
说明书范文
2014/05/07 职场文书
社会工作专业自荐信
2014/09/26 职场文书