Mocha+Typescript单元测试配置教程

安装依赖

npm i --save-dev mocha chai assert jsdom mocha-dom tsconfig-paths @types/mocha

项目根目录创建test/unit单元测试目录

mkdir -p test/unit

在test/unit目录下创建tsconfig.test.json,为测试框架提供所需的ts配置

{
  "extends": "../tsconfig.json",
  "ts-node": {
      "transpileOnly": true
  },
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "lib": ["es2017"],
    "declaration": false,
    "noImplicitAny": false,
    "removeComments": true,
    "inlineSourceMap": true,
    "moduleResolution": "node"
  },
}

在根目录创建mocha配置文件.mocharc.json 本文使用JSON配置(官方支持YAML JS JSON package.json4种配置方式)

{
  "extension": ["js", "ts", "tsx"],
  "loader": ["ts-node/esm"],
  "recursive": "test /**/*.spec.ts",
  "require": [
    "ts-node/register",
    "tsconfig-paths/register",
    "mocha-dom"
  ],
  "ui": "bdd"
}

在package.json文件中配置测试命令

{
  "name": "your-name",
  "version": "1.0.0",
  "scripts": {
    "test": "cross-env TS_NODE_PROJECT='./test/tsconfig.test.json' mocha --config .mocharc.json test/unit/**/*.spec.ts"
  }
}

测试配置是否成功

在test/unit创建demo.test.ts测试文件

import { describe, it } from "mocha";
import assert from "assert";

describe("Array", function() {
  describe("#indexOf()", function() {
    it("should return -1 when the value is not present", function() {
      assert.equal([1, 2, 3].indexOf(4), -1);
    });
  });
});

运行测试命令

npm test
配置成功

参考文献
https://mochajs.org

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

推荐阅读更多精彩内容