我开始学习应用程序测试,我需要测试该功能.
我有一些组件:
export class Countries extends React.Component<Props, State> {
private countriesList: React.RefObject<HTMLDivElement> = React.createRef<
HTMLDivElement
>();
public componentDidMount(): void {
setTimeout(this.whenCDM, 1);
}
public render(): React.ReactNode {
return (
<div ref={this.countriesList}>
</div>
);
}
private whenCDM = (): any => {
if (this.countriesList.current) {
this.whenComponentDidMount(
this.countriesList.current.getBoundingClientRect().top
);
}
};
}
我想测试一个名为whenCDM的函数,我不知道这是怎么回事.
最佳答案 我终于找到了答案.
我只是不明白什么是“模拟”.
这里是我的问题的答案:
第一.需要小型重构功能.
private whenCDM = (countriesList:any): any => {
if (countriesList.current !== null) {
this.whenComponentDidMount(
countriesList.current.getBoundingClientRect().top
);
}
};
然后在cDM中:
public componentDidMount(): void {
setTimeout(this.whenCDM(this.countriesList), 1);
}
然后在测试文件中创建模拟函数:
我想,我可以在getBoundingClientRect中设置唯一的顶级选项,但无论如何……
// ...code
it("whenCDM", () => {
const getCountriesListRef = () => {
return {
current: {
getBoundingClientRect: () => {
return {
bottom: 624,
height: 54,
left: 15,
right: 360,
top: 570,
width: 345,
x: 15,
y: 570
};
}
}
};
};
const instance = wrapper.instance();
expect(instance.whenCDM(getCountriesListRef()));
});
// ...code