Blog

Blog

PHODAL

Nodejs Mocha Chai为IoT CoAP进行测试

在上一篇——为NodeJS项目添加语法检查我们简单地说了一下,在iot-coap要提交代码时会发生的事,接着我们来说说里面的测试是怎么进行的。。

Mocha

官网是这么说的

Mocha is a feature-rich JavaScript test framework running on node.js and the browser, making asynchronous testing simple and fun. Mocha tests run serially, allowing for flexible and accurate reporting, while mapping uncaught exceptions to the correct test cases.

网上找到了一个翻译: Mocha是一个拥有非常多特征的javascript测试框架,除了能作为nodejs运行环境的测试框架外,它还支持在浏览器中做js测试框架。使用Mocha可以让javascript的异步代码测试变得简单。Mocha测试用例可以连续的执行,提供灵活和精确的测试报告,同时能在正确的测试用例中映射未捕获的异常。

IoT CoAP Mocha

安装mocha

1.直接安装

npm install -g mocha

2.通过package.json,在"devDependencies"字段中添加:

"mocha": "~1.21.4",

官方示例

示例的测试文件

var assert = require("assert")
describe('Array', function(){
  describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
      assert.equal(-1, [1,2,3].indexOf(5));
      assert.equal(-1, [1,2,3].indexOf(0));
    })
  })
})

测试

 mocha

Chai

Chai has several interfaces that allow the developer to choose the most comfortable. The chain-capable BDD styles provide an expressive language & readable style, while the TDD assert style provides a more classical feel.

Chai 是一个BDD/TDD模式的断言库.可以在node和浏览器环境下运行。添加到devDependencies中:

"devDependencies": {
    "chai": "~1.9.1",
    "mocha": "~1.21.4"
 }

Mocha Chai搭配

我们在test目录下配置了一个叫mocha.opts的文件,里面含有下面的内容,mocha会优先使用里面的参数

--reporter dot
--ui bdd
--growl
--check-leaks
--colors
--require test/common

这里的test/common是一个js文件,定义了一些全局变量

global.expect = require("chai").expect;
global.assert = require("chai").assert;
global.should = require('chai').should;

IoT CoAP BDD

在IoT CoAP测试脚本这样子的

./node_modules/.bin/mocha --growl --colors --reporter spec 2>&1

于是,以其中的一个测试为例

var resultReturn = require('../lib/coap_result_helper.js');

describe('query data status code test', function() {

    var res = function(){};
    res.end = function(){};

    it('should return 4.04 when result empty', function() {
        var request = "[]";
        resultReturn.jsonAndCode(request, res);
        var result = res.code;
        expect(result).to.eql("4.04");
    });
});

在这里我们只用以判断返回结果的Status是不是预期的结果。

于是最后我们的结果跑出来是BDD风格的。

query data status code test
    ✓ should return 4.04 when result empty
    ✓ should return 2.05 when result empty
    ✓ should return 2.05 when delete result
    ✓ should return 2.05 when save result

关于我

Github: @phodal     微博:@phodal     知乎:@phodal    

微信公众号(Phodal)

围观我的Github Idea墙, 也许,你会遇到心仪的项目

QQ技术交流群: 321689806
comment

Feeds

RSS / Atom

最近文章

关于作者

Phodal Huang

Engineer, Consultant, Writer, Designer

ThoughtWorks 技术专家

工程师 / 咨询师 / 作家 / 设计学徒

开源深度爱好者

出版有《前端架构:从入门到微前端》、《自己动手设计物联网》、《全栈应用开发:精益实践》

联系我: h@phodal.com

微信公众号: 最新技术分享

标签