From 2b94c16ce881fde488d77db499b916a45f32b93c Mon Sep 17 00:00:00 2001 From: Chris Ha Date: Thu, 23 Sep 2021 15:19:22 -0700 Subject: [PATCH] add optional `win` param to replace `window` The `window` object that is in scope for a Cypress test is not the same as the `window` in the application. Add optional param to `set` and `reset` to mock the correct `window.Date`. --- src/mockdate.ts | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/src/mockdate.ts b/src/mockdate.ts index 7803fc6..9333460 100644 --- a/src/mockdate.ts +++ b/src/mockdate.ts @@ -54,20 +54,28 @@ MockDate.toString = function() { return RealDate.toString(); }; -export function set(date: string | number | Date): void { +export function set(date: string | number | Date, win?: any): void { var dateObj = new Date(date.valueOf()) if (isNaN(dateObj.getTime())) { throw new TypeError('mockdate: The time set is an invalid date: ' + date) } - - // @ts-ignore - Date = MockDate; + + if (win) { + win.Date = MockDate; + } else { + // @ts-ignore + Date = MockDate; + } now = dateObj.valueOf(); } -export function reset(): void { - Date = RealDate; +export function reset(win?: any): void { + if (win) { + win.Date = RealDate; + } else { + Date = RealDate; + } } export default {