node.js测试框架mocha笔记

date: 2018.04.03; modification:2018.04.03

目录:

1 安装

npm i -g mocha

2 基本使用


    const mocha = require('mocha');
    const assert = require('assert');

    describe('Describe 1', function() {
        it('test case 1', () => {
            assert.equal(1, 1);
        });

        it('test case 2', () => {
            assert.equal(1, 2);
        });
    });

说明:

2.1 Setup & Teardown

如果想在每个 describe 以及 it 的开始和结尾分别做一些初始化与清理的工作怎么办呢? 代码如下:


    describe('describe1', function() {
        before(function() {
            console.log('    describe, setup');
        });

        after(function() {
            console.log('    describe, teardown');
        });

        beforeEach(function() {
            console.log('    it, setup');
        });

        afterEach(function() {
            console.log('    it, teardown');
        });

        it('test case 1', () => {
            console.log('    it 1');
            assert.equal(1, 1);
        });

        it('test case 2', () => {
            console.log('    it 2');
            assert.equal(2, 2);
        });
    });

运行结果为:

  describe1
    describe, setup
    it, setup
    it 1
    ✓ test case 1
    it, teardown
    it, setup
    it 2
    ✓ test case 2
    it, teardown
    describe, teardown

  2 passing (14ms)