node.js 测试工具介绍.
发布于 2年前 作者 ym1623 4351 次浏览

测试工具有很多,但是我个人觉得mocha是一个不错的选择.官方网址:http://visionmedia.github.com/mocha/

npm install -g mocha

首先,在项目根目录建立一个test文件夹,在该文件夹下建立一个_init.js的文件用来初始化测试文件,并把我们的开发环境改为test

process.env.NODE_ENV = 'test';

var app = require('..')
  , chai = require('chai')
  , request = require('supertest');

global.should = chai.should();
global.request = request(app);

然后继续建立一个mocha.opts文件,该文件为mocha的配置文件,在文件里面写到

--recursive 
--compilers coffee:coffee-script
-r test/_init.js

里面的–recursive的意思是文件递归,这样就不会只测试第一层文件目录的file了. –compilers的意思是编译的解释器,我习惯用coffscript语法就直接这么写了,当然,不习惯的也可以不写. -r的命令是加载初始化mocha,我们把刚写好的_init放进去就可以了 完成这些工作后去到package.json中,配置mocha执行命令,在里面加入以下代码:

"scripts": {
    "test": "mocha"
  },

这句话的意思是调用npm的命令行用test命令去执行mocha,好了,现在去test文件中加一个first_test的文件夹里面再创建test.coffee的文件或者test.js文件在里面写下以下代码:

describe 'product[@first_test](/user/first_test)', ->

  str = 'hello '

  # test to before
  before () ->
    str+='world'

  it 'should test my mocha with projects', (done) ->
    str.should.equal 'hello world'
    done()

describe 'product[@ym](/user/ym)', ->

  str = 'hello '

  # test to before
  before () ->
    str+='world'

  it 'should test my mocha with projects', (done) ->
    str.should.equal 'hello world'
    done()

其中的before方法是用来做事先加载用的,也就是异步调用. 在命令行中打 npm test 返回以下结果: enter image description here

当然,大家也可以指定运行哪些方法,或者哪些文件夹,比如在mocha.opts文件中加入一行

-g [@ym](/user/ym)  #-g是全局, 后面是正则,这样就会执行 describe product[@ym](/user/ym)'中带[@ym](/user/ym)的方法了,简单吧,具体语法大家可以去mocha官网中参考.
回到顶部