[Node.js基础]学习①⑨--编写测试mocha

http://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/00147204317563462840426beb04a849ba813eb46bb347c000

package.json

{
  "name": "mocha-test",
  "version": "1.0.0",
  "description": "Mocha simple test",
  "main": "hello.js",
  "scripts": {
    "test": "mocha"
  },
  "keywords": [
    "mocha",
    "test"
  ],
  "author": "Michael Liao",
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "https://github.com/michaelliao/learn-javascript.git"
  },
  "dependencies": {},
  "devDependencies": {
    "mocha": "3.0.2"
  }
}

hello.js

module.exports = function (...rest) {
    var sum = 0;
    for (let n of rest) {
        sum += n;
    }
    return sum;
};

test

hello-test.js

const assert = require('assert');
const sum = require('../hello');

describe('#hello.js', () => {
    describe('#sum()', () => {
        it('sum() should return 0', () => {
            assert.strictEqual(sum(), 0);
        });

        it('sum(1) should return 1', () => {
            assert.strictEqual(sum(1), 1);
        });

        it('sum(1,2) should return 3', () => {
            assert.strictEqual(sum(1, 2), 3);
        });

        it('sum(1,2,3) should return 6', () => {
            assert.strictEqual(sum(1, 2, 3), 6);
        });
    });
})

在package.json中添加npm命令:

{
  ...

  "scripts": {
    "test": "mocha"
  },

  ...
}

在hello-test目录下执行命令

C:\...\hello-test> npm test
[Node.js基础]学习①⑨--编写测试mocha_第1张图片
Paste_Image.png

before和after

hello-test.js

const assert = require('assert');
const sum = require('../hello');

describe('#hello.js', () => {
    describe('#sum()', () => {
        before(function () {
            console.log('before:');
        });

        after(function () {
            console.log('after.');
        });

        beforeEach(function () {
            console.log('  beforeEach:');
        });

        afterEach(function () {
            console.log('  afterEach.');
        });

        it('sum() should return 0', () => {
            assert.strictEqual(sum(), 0);
        });

        it('sum(1) should return 1', () => {
            assert.strictEqual(sum(1), 1);
        });

        it('sum(1, 2) should return 3', () => {
            assert.strictEqual(sum(1, 2), 3);
        });

        it('sum(1, 2, 3) should return 6', () => {
            assert.strictEqual(sum(1, 2, 3), 6);
        });
    });
});
[Node.js基础]学习①⑨--编写测试mocha_第2张图片
Paste_Image.png

你可能感兴趣的:([Node.js基础]学习①⑨--编写测试mocha)