Node.js 测试

安装与准备

$ npm init -y
$ npm i mocha -g
$ mkdir test
$ mocha

在项目目录下安装:

$ npm install mocha --save-dev
"scripts": {
  "test": "./node_modules/mocha/bin/mocha"
}

mocha:测试框架

创建:test.js

describe('TestDemo', function() {
  describe('方法 1', function() {
    context('情境 1', function() {
      it('测试 1', function() {

      })
      it('测试 2', function() {

      })
    })
  })
})
$ mocha
$ mocha run test

mocha:安排测试之前与之后要做的事

describe('TestDemo', function() {
  describe('方法 1', function() {

    before(function() {
      console.log('--- 测试之前 ---')
    })
    before(function() {
      console.log('--- 测试之后 ---')
    })

    beforeEach(function() {
      console.log('--- 每条测试之前 ---')
    })
    beforeEach(function() {
      console.log('--- 每条测试之后 ---')
    })

    context('情境 1', function() {
      it('测试 1', function() {

      })
      it('测试 2', function() {

      })
    })
  })
})

chai:断言库

安装

npm i chai --save-dev

chai:assert风格的断言

const chai = require('chai')
const assert = chai.assert

describe('TestDemo', function() {
  it('使用 assert 风格的断言测试', function() {
    //var value = 'hello'
    var value = 123
    assert.typeOf(value, 'string')
    assert.equal(value, 'hello')
    assert.lengthOf(value, 5)
  })
})
上一篇 Node.js 入门
下一篇 Nodejs crypto密码模块
目录
文章列表
1 K8S 如何选择 Docker、containerd
K8S 如何选择 Docker、containerd
2
使用yum搭建LNMP环境
使用yum搭建LNMP环境
3
PHP编译安装ldap扩展模块
PHP编译安装ldap扩展模块
4
MySQL中的索引详解
MySQL中的索引详解
5
JDK动态代理的原理
JDK动态代理的原理
最新评论
一位WordPress评论者
一位WordPress评论者
2月12日
您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 Gravatar。