diff --git a/src/util.ts b/src/util.ts index 07ec4199..48cf06db 100644 --- a/src/util.ts +++ b/src/util.ts @@ -8,7 +8,10 @@ export function getMotionName(prefixCls: string, transitionName?: string, animat } // =============================== Offset =============================== -function getScroll(w: Window, top?: boolean): number { +function getScroll(w: Window | null | undefined, top?: boolean): number { + if (!w) { + return 0; + } let ret = w[`page${top ? 'Y' : 'X'}Offset`]; const method = `scroll${top ? 'Top' : 'Left'}`; if (typeof ret !== 'number') { diff --git a/tests/util.spec.tsx b/tests/util.spec.tsx index d136d099..17a4f762 100644 --- a/tests/util.spec.tsx +++ b/tests/util.spec.tsx @@ -48,6 +48,33 @@ describe('Dialog.Util', () => { top: 1128, }); }); + + it('returns zero offset when defaultView and parentWindow are missing', () => { + const element = { + ownerDocument: {}, + getBoundingClientRect: () => ({ left: 0, top: 0 }), + } as any; + + expect(offset(element)).toEqual({ + left: 0, + top: 0, + }); + }); + + it('returns zero offset when defaultView and parentWindow are null or undefined', () => { + const element = { + ownerDocument: { + defaultView: null, + parentWindow: undefined, + }, + getBoundingClientRect: () => ({ left: 0, top: 0 }), + } as any; + + expect(offset(element)).toEqual({ + left: 0, + top: 0, + }); + }); }); describe('getMotionName', () => {