-
新建mocha-ts-demo项目
-
运行npm初始化命令
npm init -
运行typescript初始化命令
tsc --init,该命令会在项目根目录下生成tsconfig.json文件,如果报错找不到tsc,可以先运行npm install -g typescript -
安装依赖
npm install -D mocha chai @types/chai @types/mocha typescript
- 在项目根目录下创建.mocharc.json文件,并在.mocharc.json文件文件中输入以下配置
{
"spec": ["**/**/*.spec.*"], // 项目目录下所有以.spec.*结尾的文件为测试代码文件
"loader": "ts-node/esm",
"extensions": ["ts", "tsx", "js"]
}
- 在package.json文件里的script项下添加test命令
{
"name": "mocha-ts-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "mocha", // 测试命令
"build": "tsc"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@types/chai": "^4.3.5",
"@types/mocha": "^10.0.1",
"@types/sinon": "^10.0.15",
"chai": "^4.3.7",
"mocha": "^10.2.0",
"sinon": "^15.2.0",
"ts-node": "^10.9.1",
"typescript": "^5.1.6"
}
}
- 在项目根目录中创建src文件夹,在src文件夹里新建文件index.ts和index.spec.ts文件。
- 在index.ts文件中添加以下代码
export class Creature {
public greeting() {
console.log("greeting humam");
return "greeting humam";
}
}
- 在index.spec.ts文件里添加以下代码
import { assert } from "chai";
import { Creature } from "./index";
describe("First test", () => {
it("test greetint", () => {
const creature1 = new Creature();
assert.equal(creature1.greeting(), "greeting humam");
});
});
- 运行npm test,命令行终端输出如下