nodejs单元测试

目录:

  1. 测试框架
  2. 断言库
  3. supertest

1.测试框架

  nodejs的测试框架用的最多的是mocha。mocha诞生于2011年,是现在最流行的测试框架之一,再浏览器和node环境中都可以使用。它支持多种nodejs的断言库,同时支持异步和同步的测试。

  ubuntu系统下安装mocha:

npm install mocha -g

  案例:

  新建一个文件夹,文件夹下的目录分配:

  lib:存放模块代码

  test:存放单元测试代码

  package.json:包描述文件

  编写一个模块(lib/min.js)。包含一个方法,这个方法输出两个数中比较小的一个数:

exports.min = (num1, num2) => {
  if(num1 =< num2) return num1
  else return num2 
}

  给min.js编写一个对应的单元测试文件(test/min.test.js):

const min = require('../lib/min')
describe('min模块', () => {
  describe('min方法', () => {
    it('min should success', () => {
      min.min(5,6)
    })  
  })  
})

  在根目录下执行mocha:(mocha命令默认会去test文件夹下寻找测试文件)

  min模块
    min方法
      ✓ min should success


  1 passing (5ms)

  但是上面的测试有一个很大缺点,并没有判断运行之后能不能得到正确结果5,这是因为测试没有加上断言库的原因,下面介绍断言库。   

2.断言库

  上面案例中只运行了代码,并没有检测结果是否是预期的结果,如果要对结果加以判断,还需要使用断言库:

  • should.js
  • supertest.js(用于http请求测试)

  使用should为测试加上断言:

1)should

  安装should:

sudo npm install should --save   --registry=http://registry.npm.taobao.org

  加上断言:

const min = require('../lib/min')
const should =  require('should')

describe('min模块', () => {
  describe('min方法', () => {
    it('min should success', () => {
      min.min(5,6).should.be.equal(5)
    })  
  })  
})

  此时再命令行再次输入mocha:

  min模块
    min方法
      ✓ min should success


  1 passing (6ms)

  和上面的结果一样,但是意义却不一样了。

  异步测试

  在lib中增加异步函数:

exports.asy = (bk) => {
  setTimeout(() => {
    bk(5)
  }, 10) 
}

  在test文件夹中增加对应的测试文件:

const asy = require('../lib/asy')

describe('asy模块', () => {
  it('asy函数', done => {
    asy.asy(result => {
console.log(result) done() }) }) })

3.supertest

再用nodejs做web开发的时候,模拟http请求时是必不可少的,当然使用浏览器也可以方便的实现http请求测试,但是并不快捷。supertest是一个非常好的适用于node的模拟http请求的库。

方法:

.set()  用来设置数据

.expect()  用来断言,如:.expect(200)

.send()  用来发送表单域数据,比如一个登录模块

.attach()  主要用来测试文件上传,由于send()只能上传文本域,所以关于multipart-file的上传需要通过附件来绑定。

持久化Cookie:

  再很多业务中,需要用户先登录才有权限执行操作,这个时候作为http请求模拟,必须要可以保存一些Cookie数据,也就是回话持久化,两种思路:

  1)再supertest中,可以一个agent对象,这个对象的API跟直接在supertest上调用各种方法是一样的,这个request再被多次调用get和post之后,可以一路把cookie都保存下来

  2)通过.set(),再发起请求时,调用.set('Cookie', 'a cookie string')

let request  = require('uspertest')
let userCookie
request.post('login')
.end((err, res)  => {
  userCookie = res.header['Cookie']  
})

request.post(''createddd)
    .set('Cookie', userCookie)
    .end(...)

supertest使用的demo:地址