Jest 单元测试时,在逻辑层中使用 Page 提示 Page is not defined,何解?
基础库:2.11.0 Jest: 29.4.1 babel-jest: 29.4.1 miniprogram-simulate: 1.5.8 miniprogram-api-typings: 2.8.3-1 Jest 测试文件 // jest-example\__tests__\custom-component.test.ts
import simulate from 'miniprogram-simulate';
import { test, expect } from '@jest/globals';
import path from 'path';
test('custom-component test', () => {
const dirname = path.resolve(__dirname, '../custom-component');
const id = simulate.load(dirname); // 此处必须传入绝对路径
const comp = simulate.render(id); // 渲染成自定义组件树实例
const parent = document.createElement('parent-wrapper'); // 创建父亲节点
comp.attach(parent); // attach 到父亲节点上,此时会触发自定义组件的 attached 钩子
const view = comp.querySelector('.index'); // 获取子组件 view
expect(view?.dom).toBeDefined();
expect(view?.dom?.innerHTML).toBe('index.properties'); // 测试渲染结果
if (view?.dom) {
expect(window.getComputedStyle(view?.dom)?.color).toBe('green'); // 测试渲染结果
} else {
console.error('view.dom is undefined');
}
});
组件逻辑层 // jest-example\custom-component.ts
Page({
properties: {
prop: {
type: String,
value: 'index.properties',
},
},
});
运行 yarn jest 报错 ReferenceError: Page is not defined
> 1 | Page({
| ^
2 | properties: {
3 | prop: {
4 | type: String,
at Object.Page (miniprogram/pages/jest-example/custom-component.ts:1:1)
但是将 Page 改为 Component 就可以正常运行 Component({
properties: {
prop: {
type: String,
value: 'index.properties',
},
},
});
$ jest
PASS miniprogram/pages/jest-example/__tests__/custom-component.test.ts
√ custom-component test (98 ms)
百思不得其解,希望能得到社区的解答,万分感谢。