使用jasmine-node 进行NodeJs单元测试 环境搭建

关于jasmine就不多说了,关于语法请参加官方文档。http://pivotal.github.io/jasmine/ 

关于NodeJS的单元测试框架有多种,如果要在NodeJS中使用jasmine的话 ,需要安装jasmine-node. 采用npm安装即可。github地址 https://github.com/mhevery/jasmine-node

全局安装 jasmine-node 。  npm install jasmine-node -g  安装完之后环境基本也算是搭建好了。下面写个Demo。

编写我们NodeJS的功能js代码  。新建一个目录 test  

新建我们要编写的js功能文件BubbleSort.js 

这里就拿冒泡排序来说吧 .具体算法可以忽略,功能就是将一个数组从小到大排序

 function BubbleSort(arr) { //交换排序->冒泡排序
  var st = new Date();
  var temp;
  var exchange;
  for(var i=0; i<arr.length; i++) {
   exchange = false;
   for(var j=arr.length-2; j>=i; j--) {
    if((arr[j+1]) < (arr[j])) {
     temp = arr[j+1];
     arr[j+1] = arr[j];
     arr[j] = temp;
     exchange = true;
    }
   }
   if(!exchange) break;
  }
  return arr;
 }

  

接下来就可以编写测试代码了 文件名 testspec.js

var BubbleSort = require('./BubbleSort.js'); //引入BubbleSort.js 
        describe('basic tests', function(){   
      it('test sample', function(){
          expect(BubbleSort.BubbleSort([42,75,84,63,13])).toEqual([13,42,63,75,84]);
          });
        });

代码已经编写完了。cmd打开控制台进入test文件夹。运行 jasmine-node testspec.js

下面修改下代码。故意搞错  expect(BubbleSort.BubbleSort([42,75,84,63,13])).toEqual([42,13,63,84,75])。

重新运行 jasmine-node testspec.js

当然也可以进行自动的测试,也可以增加 --autotest选项,当文件发生变化的时候进行自动测试 jasmine-node --autotest  testspec.js。 。启动一次 会自动监控文件的变化,也可以通过 --watch 路径 。来检测变化的文件。

同时也支持对异步的测试。比如我用express 写两个简单的服务 核心代码如下

app.get('/username',function(req, res){
  res.send("kunkun");
});

在浏览器中访问localhost:3000/username

 以上准备好了一个服务。

我们已经清楚,下面在代码里进行异步的访问测试。使用request 模块可以方便地来访问服务。使用方式请参考https://github.com/mikeal/request

先使用npm来安装,进入 test 文件夹运行  npm install request 。修改测试代码testspec.js 

 var request = require('request');
     describe('asyc tests', function(){   
it("should respond with kunkun", function(done) {
 	 request("http://localhost:3000/username", function(error, response, body){
 	   expect(body).toEqual("kunkun");
	    done();
	  });
	});
});

  测试通过。

主意事项  测试代码的名字 一定要以 spec.js来结尾,比如我的测名代码的名字为testspec.js。如果测试代码是coffee格式 要以 spec.coffee来结尾。否则jasmine会不认的。。

官方解释如下:

Write the specifications for your code in *.js and *.coffee files in the spec/ directory. You can use sub-directories to better organise your specs. Note: your specification files must be named as *spec.js, *spec.coffee or *spec.litcoffee, which matches the regular expression /spec.(js|coffee|litcoffee)$/i; otherwise jasmine-node won't find them! For example, sampleSpecs.js is wrong, sampleSpec.js is right.

 

关于更多的内容请参考 https://github.com/mhevery/jasmine-node 。自己down下来慢慢研究吧,里面有不少测试的例子。

原文地址:https://www.cnblogs.com/dubaokun/p/3398694.html