increase BackTop code coverage (#18406)

This commit is contained in:
偏右 2019-08-22 18:04:10 +08:00 committed by GitHub
parent b9b9675fe1
commit 371ba4d819
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 23 deletions

View File

@ -19,4 +19,27 @@ describe('BackTop', () => {
expect(window.pageYOffset).toBe(0);
scrollToSpy.mockRestore();
});
it('could be unmount without error', async () => {
const wrapper = mount(<BackTop />);
expect(() => {
wrapper.unmount();
}).not.toThrow();
});
it('support onClick', async () => {
const onClick = jest.fn();
const wrapper = mount(<BackTop onClick={onClick} visibilityHeight={-1} />);
const scrollToSpy = jest.spyOn(window, 'scrollTo').mockImplementation((x, y) => {
window.scrollY = y;
window.pageYOffset = y;
});
window.scrollTo(0, 400);
// trigger scroll manually
wrapper.instance().handleScroll();
await sleep();
wrapper.find('.ant-back-top').simulate('click');
expect(onClick).toHaveBeenCalled();
scrollToSpy.mockRestore();
});
});

View File

@ -47,33 +47,13 @@ export default class BackTop extends React.Component<BackTopProps, any> {
}
}
setScrollTop(value: number) {
const getTarget = this.props.target || getDefaultTarget;
const targetNode = getTarget();
if (targetNode === window) {
document.body.scrollTop = value;
document.documentElement!.scrollTop = value;
} else {
(targetNode as HTMLElement).scrollTop = value;
}
}
getCurrentScrollTop = () => {
const getTarget = this.props.target || getDefaultTarget;
const targetNode = getTarget();
if (targetNode === window) {
return window.pageYOffset || document.body.scrollTop || document.documentElement!.scrollTop;
}
return (targetNode as HTMLElement).scrollTop;
};
scrollToTop = (e: React.MouseEvent<HTMLDivElement>) => {
const { target = getDefaultTarget } = this.props;
const { target = getDefaultTarget, onClick } = this.props;
scrollTo(0, {
getContainer: target,
});
if (typeof this.props.onClick === 'function') {
this.props.onClick(e);
if (typeof onClick === 'function') {
onClick(e);
}
};