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 Flutter列表侧滑菜单组件实现
Flutter列表侧滑菜单组件实现
2
Spring Cloud使用Nacos作为服务配置中心
Spring Cloud使用Nacos作为服务配置中心
3
Android 7.0及以上FileProvider巨坑Failed to find configured root that contains
Android 7.0及以上FileProvider巨坑Failed to find configured root that contains
4
Java服务端开发记录
Java服务端开发记录
5
Spring Cloud Gray 采坑记录
Spring Cloud Gray 采坑记录
最新评论
一位WordPress评论者
一位WordPress评论者
2月12日
您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 Gravatar。