1. 安装依赖
```json
"devDependencies": {
"jsdom": "^21.1.1",
"miniprogram-simulate": "^1.5.9",
"typescript": "^5.0.2",
"vite": "^4.2.1",
"vitest": "^0.29.5"
}
```
2. 配置文件
```ts
// vitest.config.ts
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
globals: true,
environment: "jsdom",
},
});
```
> 💡: 当配置globals字段值为true时, 为保证全局API具有类型,需要在tsconfig增加类型引用
```json
// tsconfig.json
{
"compilerOptions": {
// ...
"types": ["vitest/globals"]
}
// ...
}
```
3. 修改miniprogram-simulate源文件(当前版本为"1.5.9")
```js
// path: node_modules\miniprogram-simulate\src\utils.js
// 修改 setNodeJsEnv函数 内容 require(filePath) --> require(filePath + '.ts');
// 修改前
function setNodeJsEnv() {
env = "nodejs";
fs = require("fs");
compiler = require(compilerName);
runJs = filePath => {
require(filePath); // 需要修改的部分
delete require.cache[require.resolve(filePath)];
};
}
// 修改后
function setNodeJsEnv() {
env = "nodejs";
fs = require("fs");
compiler = require(compilerName);
runJs = filePath => {
require(filePath + ".ts"); // 修改的部分
delete require.cache[require.resolve(filePath)];
};
}
```
> 💡 不修改时,require(filePath) 加载的可能是 组件目录下的 xxx.json文件而非.ts(js)文件,造成错误。但在使用jest搭配miniprogram-simulate测试时无需修改。这问题出现在使用vitest时。当前的miniprogram-simulate为1.5.9版本
3. 测试用例demo
```html
<!--components/demo/demo.wxml-->
<text id="name">{{ name }}</text>
```
```ts
// components/demo/demo.ts
Component({
properties: {
name: String,
},
});
```
```ts
// components/demo/demo.test.ts
import { load, render } from "miniprogram-simulate";
import path from "path";
describe("demo", () => {
// 读取组件
const id = load(path.resolve(__dirname, "demo"));
// mock传入的properties
const properties = {
name: "hry",
};
// 渲染组件
const component = render(id, properties);
// 建立父节点
const parent = document.createElement("parent-wrapper");
// 挂载组件到父节点
component.attach(parent);
test("渲染值与传入name值相等", async () => {
const comp = component.querySelector("#name");
expect(comp!.dom!.textContent).toBe(properties.name);
});
});
```
4. [demo代码片段](https://developers.weixin.qq.com/s/ErAvwSmu7YGb)
5. 总结
vitest搭配ts和miniprogram-simulate配置相对简单,运行较快,可兼容jest测试用例。但需要改动miniprogram-simulate(1.5.9)源码。jest 搭配ts 配置相对复杂(需要插件ts-jest)。共同问题是watch模式下wxml文件改动不会自动运行(或许是我没找到对应的配置)。就说这么多吧,理解不到的地方请指正。