I start learn app testing and me need to test the function. I have some component:
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
);
}
};
}
I want to test function named whenCDM, and i don't know how do this right.
I finally find the answer. I just did not understand what is the "mock".
Here the answer on my question:
First. Need small refactor the function.
private whenCDM = (countriesList:any): any => {
if (countriesList.current !== null) {
this.whenComponentDidMount(
countriesList.current.getBoundingClientRect().top
);
}
};
Then in cDM:
public componentDidMount(): void {
setTimeout(this.whenCDM(this.countriesList), 1);
}
Then create mock function in test file: i guess, i can set in getBoundingClientRect only top option, but anyway...
// ...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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With