From 11396a21de8f9a35ba219d5fa5e0c31f6f7c4311 Mon Sep 17 00:00:00 2001 From: Aakansha Doshi Date: Tue, 28 Dec 2021 17:17:41 +0530 Subject: [PATCH] fix: check if process is defined before using so it works in browser (#4497) * refactor: use isTestEnv() utils where applicable * check if process is defined --- src/element/newElement.ts | 4 ++-- src/random.ts | 4 ++-- src/utils.ts | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/element/newElement.ts b/src/element/newElement.ts index f0ab9e4c..3121dd85 100644 --- a/src/element/newElement.ts +++ b/src/element/newElement.ts @@ -13,7 +13,7 @@ import { FontFamilyValues, ExcalidrawRectangleElement, } from "../element/types"; -import { getFontString, getUpdatedTimestamp } from "../utils"; +import { getFontString, getUpdatedTimestamp, isTestEnv } from "../utils"; import { randomInteger, randomId } from "../random"; import { mutateElement, newElementWith } from "./mutateElement"; import { getNewGroupIdsForDuplication } from "../groups"; @@ -369,7 +369,7 @@ export const duplicateElement = >( overrides?: Partial, ): TElement => { let copy: TElement = deepCopyElement(element); - if (process.env.NODE_ENV === "test") { + if (isTestEnv()) { copy.id = `${copy.id}_copy`; // `window.h` may not be defined in some unit tests if ( diff --git a/src/random.ts b/src/random.ts index 3335f729..851bc28e 100644 --- a/src/random.ts +++ b/src/random.ts @@ -1,5 +1,6 @@ import { Random } from "roughjs/bin/math"; import { nanoid } from "nanoid"; +import { isTestEnv } from "./utils"; let random = new Random(Date.now()); let testIdBase = 0; @@ -11,5 +12,4 @@ export const reseed = (seed: number) => { testIdBase = 0; }; -export const randomId = () => - process.env.NODE_ENV === "test" ? `id${testIdBase++}` : nanoid(); +export const randomId = () => (isTestEnv() ? `id${testIdBase++}` : nanoid()); diff --git a/src/utils.ts b/src/utils.ts index 82ab78d1..6766de40 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -443,8 +443,7 @@ export const bytesToHexString = (bytes: Uint8Array) => { .join(""); }; -export const getUpdatedTimestamp = () => - process.env.NODE_ENV === "test" ? 1 : Date.now(); +export const getUpdatedTimestamp = () => (isTestEnv() ? 1 : Date.now()); /** * Transforms array of objects containing `id` attribute, @@ -459,4 +458,5 @@ export const arrayToMap = ( }, new Map()); }; -export const isTestEnv = () => process?.env?.NODE_ENV === "test"; +export const isTestEnv = () => + typeof process !== "undefined" && process.env?.NODE_ENV === "test";