[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
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);
        });
    });
});
Paste_Image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,992评论 19 139
  • JavaScript 模块化编程 网站越来越复杂,js代码、js文件也越来越多,会遇到什么问题? 命名冲突; 文件...
    magic_pill阅读 1,476评论 0 1
  • Node.js学习 官方定义: Node.js运行环境是在Chrome的V8 JavaScript引擎上. Nod...
    荞叶阅读 609评论 0 2
  • 无意中看到zhangwnag大佬分享的webpack教程感觉受益匪浅,特此分享以备自己日后查看,也希望更多的人看到...
    小小字符阅读 8,242评论 7 35
  • 随着2017年的春季番逐渐走向正轨,许多优秀的作品也逐渐的抢占了各位观众老爷的视线。今天就给大家推荐一部2016年...
    远坂宗政阅读 1,288评论 2 0