@kooboo/vitest-plugin
v0.0.3
Published
A Vitest plugin for Kooboo.
Readme
@kooboo/vitest-plugin
一个自定义的 Vitest 插件。
安装
npm install vitest @kooboo/vitest-plugin --save-dev使用方法
1. 项目根目录下添加vitest.config.ts
在 vitest.config.ts 中添加@kooboo/vitest-plugin的引用以及配置setupFiles:
import { resolve } from "node:path";
import { defineConfig } from "vitest/config";
import koobooPlugin from "@kooboo/vitest-plugin";
export default defineConfig({
resolve: {
alias: {
"@": resolve(__dirname, "src"),
},
},
test: {
globals: true,
environment: "node",
include: ["tests/**/*.spec.ts"],
setupFiles: ["tests/kooboo.setup.ts"], // 插件自动生成的setup文件
},
plugins: [koobooPlugin()],
});在.gitignore中忽略tests/kooboo.setup.ts文件,防止插件自动生成的setup文件被提交到代码仓库。
kooboo.setup.ts2. 创建tests文件夹以及tsconfig.json
在项目根目录下创建tests文件夹,并在其中创建tsconfig.json文件,内容如下:
{
"compilerOptions": {
"paths": {
"@/*": ["../src/*"]
},
"types": ["../kooboo.d.ts"]
}
}3. 在package.json中添加"test": "vitest"
在package.json文件的scripts字段中添加"test": "vitest",这样就可以使用npm test命令来运行测试了。
4. 编写测试用例
在tests文件夹中编写测试用例,测试用例的文件命名规则为*.spec.ts, 例如tests/service.spec.ts。
// `src/code/service.ts`
export function sayHello(name: string) {
const url = k.site.getHomeUrl()
return `hello ${name}, from ${url}`;
}// `tests/service.spec.ts`
import { describe, it, expect, vi } from "vitest";
import { sayHello } from "@/code/service";
describe("service", () => {
it("sayHello should work correctly", () => {
// 1. mock kooboo function
vi.spyOn(k.site, "getHomeUrl").mockReturnValue("https://mock.kooboo.com");
// 2. call sayHello function
const result = sayHello("kooboo");
// 3. assert result
expect(result).toBe("hello kooboo, from https://mock.kooboo.com");
});
});License
MIT
