先看下我的demo目录结构,lib下是待测试源代码。test下是mocha配置文件以及测试案例文件,接下来一步一步来用mocha来测试js以及typescript

工程结构

1、先安装mocha及其依赖项

npm init 一路next初始化,此时生成package.json

npm init 

 然后安装mocha及其依赖模块,断言我采用chai模块配合mocha

npm install --save-dev mocha
npm install --save-dev chai
npm install --save-dev @types/mocha
npm install --save-dev @types/chai

这个几个模块就可以编写出es5 规范的测试脚本了

2、编写es5规范的测试案例

在lib下新建add.js

var add = function(a,b){
    return a + b;
}
module.exports= add;

在test下新建 add.test.js,describe 也称为test suite,即“测试套件”,是可以嵌套的。一个describe可以有多个it,一个it代表一个测试用例。it里面又可以有多个expect,当然expect是chai 暴露出来的一种接口形式,我们也可以使用Assert、Should。

var add = require("../lib/add");
var expect = require("chai").expect;

describe('加法函数测试',function(){
    it('1+1应该等于2',function(){
        expect(add(1,1)).to.be.equal(2);
    })
})

在package.json的script下新加 "test": "mocha ./test/*.js"

"scripts": {
    "test": "mocha ./test/*.js"
 }

 然后执行npm run test,会看到控制台输出如下时就表示这个测试案例通过了

这样就完成了一个es5规范的js的测试,那接下来问题来了,对于es6的我们该怎么处理,请看下面

3、编写es6的测试案例

在lib下新建es6.js,test下编写测试代码es6.test.js

let square = function(n){
    return n*n;
};
export default  square;
import square from "../lib/es6";
let expect = require("chai").expect;

describe('square函数测试',function(){
    it('2的平方应该等于4',function(){
        expect(square(2)).to.be.equal(4);
    })
})

 这时候直接运行npm run test会报错,对于es6预发我们需要使用babel-register模块

首先安装一下

npm install --save-dev babel-register

然后修改一下package.json的script

"scripts": {
    "test":"mocha  -r babel-core/register ./test/*.js"
 }

在执行npm run test就可成功执行针对es6的测试案例

3、编写typescript测试案例

在lib下新建helloTs.ts,test下编写测试代码helloTs.test.ts

function hello():string{
    return 'hello World';
}
export default hello;
import hello from '../lib/helloTs';
import {expect} from 'chai';
import 'mocha';

describe("hello function测试",function(){
    it('应该返回hello world',function(){
        const result = hello();
        expect(result).to.equal("hello World");
    })
})

 然后修改一下package.json的script,新加一条"testTs": "mocha -r ts-node/register ./test/*.ts",当然要想处理typescript需要先安装typescript、ts-node模块

npm install --save-dev typescript
npm install --save-dev ts-node

package.json的script变为

"scripts": {
    "test": "mocha  -r babel-core/register ./test/*.js",
    "testTs": "mocha -r ts-node/register ./test/*.ts"
  },

然后执行npm run testTs即可

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐