安装依赖
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
网友评论