单元测试 -- mocha + chai

栏目: 编程语言 · 发布时间: 7年前

内容简介:单元测试是用来对一个模块、一个函数或者一个类来进行正确性检验的测试工作可以理解为对功能的基本验证目前node中的测试框架,一般使用的是 mocha + 断言库 chai
单元测试 -- mocha + chai

单元测试

单元测试是用来对一个模块、一个函数或者一个类来进行正确性检验的测试工作

可以理解为对功能的基本验证

目前node中的测试框架,一般使用的是 mocha + 断言库 chai

安装

npm install mocha -g
npm install mocha
npm install chai
复制代码

mocha && chai

mocha API

describe

describe 是一个 用例测试集, 他可以进行嵌套

describe('进行首页的测试', function() {
  // ....
})
复制代码

it

一个it对应一个单元测试用例

it('测试接口xxx', function() {
  // ....
})
复制代码

only skip

only -- 在当前的父describe块下,只执行该单元的测试

skip -- 在当前的父describe块下,跳过该单元的测试

describe('Array', function() {
  describe.only('父describe块下只执行该测试单元', () => {
    it.skip('跳过的测试单元', () => { });
  })
})
复制代码

describe 和 it 都可以使用这两个方法

timeout - 设超时

测试集合上定义超时时间,会对这个测试集合中所有的测试用例和测试集合起作用

const sleep = time => new Promise(resolve => setTimeout(resolve, time))
 it('timeout', async function () {
    this.timeout(1000)
    await sleep(3000)
    expect(true).to.be.ok
  })
复制代码
单元测试 -- mocha + chai

hooks

提供了几个函数,在特定的事件发生时被触发

before()、after()、beforeEach()、afterEach()

同一个describe下的执行顺序为before、beforeEach、afterEach、after

before, after 执行一次

beforeEach,afterEach 每一个测试用例都会触发一次

before(() => console.info('首页测试开始'))
after(() => console.info('首页测试结束'))

beforeEach('check check check ', function() {
  console.log('i am check')
})
复制代码

chai API

chai有三种断言风格,expect,should,assert, 我的项目使用的是 expect

expect

列出几个常用的方法

方法 含义
equal 相等(严格比较)
not 取反
include 包含
  • 判断数据类型
expect('username').to.be.a('string')
    expect(false).to.be.a('boolean')
    expect(obj).to.have.property('foo')
复制代码

异步测试

项目中的大部分函数为异步的,这个需要借助 done 来处理

it(`处理异步请求`, (done) => {
  // ...
  done()
})
复制代码

异步函数在函数内部手动调用done()表示测试成功,done(err)表示测试出错

async await 可以不使用done

it('更新用户对于文章的态度', async () => {
    const result = await updateAttitude({ articleId: 123, userId: 131, status: 0})
    expect(result).to.be.a('number')
  })

复制代码

最常见的接口测试

it('获取某一个频道下的所有文章列表', async function ()  {
    const result = await chai
      .request(app)
      .get('/articles/3/1')
      .then((res) => {
        return res.body
      })
    expect(result).to.have.property('data')
  })
复制代码

测试结果检查

测试报告

生成测试报告使用的是 mochawesome 模块

"mocha:report": "mocha --reporter mochawesome"
复制代码

会自动在项目创建 一个 mochawesome-report 目录,

单元测试 -- mocha + chai

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Ordering Disorder

Ordering Disorder

Khoi Vinh / New Riders Press / 2010-12-03 / USD 29.99

The grid has long been an invaluable tool for creating order out of chaos for designers of all kinds—from city planners to architects to typesetters and graphic artists. In recent years, web designers......一起来看看 《Ordering Disorder》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

html转js在线工具
html转js在线工具

html转js在线工具