Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

不能直接测试的原因

Cannot read properties of undefined (reading '@@initialState')
报错 Cannot read properties of undefined (reading ‘@@initialState’)
看源码
源码
useModel在内部是使用了useContext(),测试组件时在上层并没有对应的Provider,所以读取不到UniContext,更拿不到@@initialState

实现方案

在测试该组件时定义应该父组件UniContext.Provider,在这里提前指定好context。
这里简单封装一下,因为是简单实现所以没写更多的功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { UmiContext } from '@/.umi/plugin-model/helpers/constant';
import React from 'react';

interface ITestModelProps {
data: Record<string, any>;
}

const TestModel: React.FunctionComponent<ITestModelProps> = (props) => {
const callbackSet = new Set([() => {}]);
const callbacks: Record<string, Set<() => void>> = {};
Object.keys(props.data).forEach((item) => {
callbacks[item] = callbackSet;
});
const update = (namespace: string) => {
callbacks[namespace].forEach((callback: (val: any) => void) => {
callback(props.data);
});
};
return (
<UmiContext.Provider
value={{
data: props.data,
callbacks,
update,
}}
>
{props.children}
</UmiContext.Provider>
);
};

export default TestModel;

使用方式

1
2
3
4
5
6
7
8
9
10
11
12
13
test('test Home page', async () => {
//...省略mock获取数据
const ins = render(
<TestModel
data={{
'@@initialState': { initialState: { currentUserInfo, settings: defaultSettings } },
}}
>
<Home />
</TestModel>,
);
//...省略测试内容
}

相关GitHub Issues 链接