安装必要的包

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



分别填写下面几项,关于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下面的输出框中有测试的结果,绿色表示通过,红色表示失败。

断言库的使用

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);
});

PHPStorm中对nodejs项目进行单元测试的更多相关文章

  1. 在Linux系统中部署NodeJS项目

    在Linux系统中部署NodeJS项目 安装NodeJS 首先进入 Node 官网,下载对应的 Node包 下载下来后是一个后缀为 xz 的压缩包,我们把这个包上传到 Linux 系统中的 /usr/ ...

  2. 在WebStorm环境中给nodejs项目中添加packages

    照前文 http://www.cnblogs.com/wtang/articles/4133820.html  给电脑设置了WebStorm的IDE的nodejs开发环境.新建了个express的网站 ...

  3. Phpstorm配置phpunit对php进行单元测试

    在 phpstorm 中配置 php 项目的单元测试,项目使用 Composer 进行管理,为了避免在项目中直接引入 phpunit 相关代码包,使项目的 vendor 目录变得臃肿,这里采用全局安装 ...

  4. 如何在NodeJS项目中优雅的使用ES6

    如何在NodeJS项目中优雅的使用ES6 NodeJs最近的版本都开始支持ES6(ES2015)的新特性了,设置已经支持了async/await这样的更高级的特性.只是在使用的时候需要在node后面加 ...

  5. SVN checkout 出的项目在PHPstorm中打开没有subversion(SVN)选项按钮怎么办?

    对于svn add 命令的批量操作,为了操作简便还是习惯在IDE中完成,有时候新checkout出的项目,在PHPstorm中右键菜单中没有 Subversion 按钮,操作如下: 点击VCS按钮,然 ...

  6. VS中怎样对C#项目进行单元测试

    场景 SpringBoot+Junit在IDEA中实现查询数据库的单元测试: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/927 ...

  7. phalcon: Windows 下 Phalcon dev-tools 配置 和 Phpstorm中配置Phalcon 代码提示, phalcon tools的使用

    准备: phalcon-devtools包 下载地址: https://github.com/phalcon/phalcon-devtools 解压到wampserver的www目录 (xampp 用 ...

  8. 为WPF项目创建单元测试

    原文作者: 周银辉  来源: 博客园 原文地址:http://www.cnblogs.com/zhouyinhui/archive/2007/09/30/911522.html 可能你已发现一个问题, ...

  9. PhpStorm创建Drupal模块项目开发教程(4)

    编码器是一个检查和操纵代码的Drupal-specific工具. 探测器则是发现异常代码,通常被用于开发中的编码错误预警. 接下来将介绍编码器与探测器在PhpStorm中整合工作的各个步骤,实现PHP ...

随机推荐

  1. CentOS7 配置SVN服务器

    也可以参考这里:https://jingyan.baidu.com/article/148a1921d84be34d71c3b18f.html 1.安装svn yum install -y subve ...

  2. java可用与串口通信的一些库

    java原生对串口的支持只有javax.comm,javax.comm比较老了,而且不支持64位系统,我在看jlibmodbus(一个java实现的modbus协议栈)的时候发现了几个可供使用的jav ...

  3. selenium IDE 使用方法整理

    1.设置起始点(确定case从哪步开始执行),快捷键:S,效果图如下: 2.设置断点(case执行到添加断点处,将自动停止),快捷键:B,效果图如下: 3.设置判断点    如:百度输入ceshi,点 ...

  4. SpringBoot进阶教程(二十九)整合Redis 发布订阅

    SUBSCRIBE, UNSUBSCRIBE 和 PUBLISH 实现了 发布/订阅消息范例,发送者 (publishers) 不用编程就可以向特定的接受者发送消息 (subscribers). Ra ...

  5. 第一课《.net之--泛型》

    今天我来学习泛型,泛型是编程入门学习的基础类型,从.net诞生2.0开始就出现了泛型,今天我们开始学习泛型的语法和使用. 什么是泛型? 泛型(generic)是C#语言2.0和通用语言运行时(CLR) ...

  6. Java中三目运算符不为人知的坑

    一.思考题 以下代码可能有什么错误?为什么? import java.util.HashMap; import java.util.Map; public class Test { public st ...

  7. Eclipse4JavaEE安装SpringBoot

    第一步:下载SpringBoot SpringBoot官网下载链接 第二步:在Eclipse里进行安装 打开Eclipse,菜单栏Help ->Install New Software,进入下图 ...

  8. 号称“新至强,可拓展,赢当下”的Xeon可拓展处理器有多逆天?

    目前企业数据中心正在发生重大变化,许多企业正在经历基于在线服务和数据的广泛转型.他们将这些数据用于功能强大的人工智能和分析应用程序,这些应用程序可以将其转化为改变业务的洞察力,然后推出可以使这些洞察力 ...

  9. 如何只在IE上加载CSS样式表

    前言:IE一直是特殊的一个浏览器,我们可以使用一些方法来指定样式表只在IE浏览器下被加载. IE9以及低于IE9版本 : 可以使用条件注释语句来加载特定于ie的样式表.如下所示,使用外部css3样式表 ...

  10. 《iOS 11 安全区域适配总结》

    本文来自于腾讯Bugly公众号(weixinBugly),作者:sonialiu,未经作者同意,请勿转载,原文地址:http://mp.weixin.qq.com/s/W1_0VrchCO50owhJ ...