不能直接测试的原因
报错 Cannot read properties of undefined (reading ‘@@initialState’)
看源码
useModel在内部是使用了useContext(),测试组件时在上层并没有对应的Provider,所以读取不到UniContext,更拿不到@@initialState
实现方案
在测试该组件时定义应该父组件UniContext.Provider,在这里提前指定好context。
这里简单封装一下,因为是简单实现所以没写更多的功能
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;
使用方式
test('test Home page', async () => {
//...省略mock获取数据
const ins = render(
<TestModel
data={{
'@@initialState': { initialState: { currentUserInfo, settings: defaultSettings } },
}}
>
<Home />
</TestModel>,
);
//...省略测试内容
}