From 6404fc7869103e84c7f9b0c0f8ac691ccc244288 Mon Sep 17 00:00:00 2001 From: Blaine Kasten Date: Fri, 10 Jul 2020 13:55:11 -0500 Subject: [PATCH] fix(gatsby-link): Do not crash in unit tests when globals are undefined (#25608) * fix(gatsby-link): Do not crash in unit tests when globals are undefined * wrap in production checks * different approach * Revert "different approach" This reverts commit 91a894b13ccdf794575237aee0d7c733ad5f8414. --- packages/gatsby-link/src/__tests__/index.js | 4 ++-- packages/gatsby-link/src/index.js | 21 ++++++++++++++++++--- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/packages/gatsby-link/src/__tests__/index.js b/packages/gatsby-link/src/__tests__/index.js index 82eaefb5c9dc9..c2a4b62956937 100644 --- a/packages/gatsby-link/src/__tests__/index.js +++ b/packages/gatsby-link/src/__tests__/index.js @@ -94,8 +94,8 @@ describe(``, () => { }) it(`does not fail with missing __BASE_PATH__`, () => { - global.__PATH_PREFIX__ = `` - global.__BASE_PATH__ = undefined + delete global.__PATH_PREFIX__ + delete global.__BASE_PATH__ const source = createMemorySource(`/active`) diff --git a/packages/gatsby-link/src/index.js b/packages/gatsby-link/src/index.js index 052a3d98a85eb..7206979c63e8d 100644 --- a/packages/gatsby-link/src/index.js +++ b/packages/gatsby-link/src/index.js @@ -9,7 +9,7 @@ export { parsePath } const isAbsolutePath = path => path?.startsWith(`/`) -export function withPrefix(path, prefix = __BASE_PATH__) { +export function withPrefix(path, prefix = getGlobalBasePrefix()) { if (!isLocalLink(path)) { return path } @@ -17,13 +17,28 @@ export function withPrefix(path, prefix = __BASE_PATH__) { if (path.startsWith(`./`) || path.startsWith(`../`)) { return path } - const base = prefix ?? __PATH_PREFIX__ ?? `/` + const base = prefix ?? getGlobalPathPrefix() ?? `/` return `${base?.endsWith(`/`) ? base.slice(0, -1) : base}${ path.startsWith(`/`) ? path : `/${path}` }` } +// These global values are wrapped in typeof clauses to ensure the values exist. +// This is especially problematic in unit testing of this component. +const getGlobalPathPrefix = () => + process.env.NODE_ENV !== `production` + ? typeof __PATH_PREFIX__ !== `undefined` + ? __PATH_PREFIX__ + : undefined + : __PATH_PREFIX__ +const getGlobalBasePrefix = () => + process.env.NODE_ENV !== `production` + ? typeof __BASE_PATH__ !== `undefined` + ? __BASE_PATH__ + : undefined + : __BASE_PATH__ + const isLocalLink = path => path && !path.startsWith(`http://`) && @@ -31,7 +46,7 @@ const isLocalLink = path => !path.startsWith(`//`) export function withAssetPrefix(path) { - return withPrefix(path, __PATH_PREFIX__) + return withPrefix(path, getGlobalPathPrefix()) } function absolutify(path, current) {