我开始学习应用测试,我需要测试功能。 我有一些组件:
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 中设置 top 选项,但无论如何...
// ...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
关于javascript - 如何用 Jest/ enzyme 来模拟 react refs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52839909/