Skip to content

Commit

Permalink
fix(gatsby-link): Do not crash in unit tests when globals are undefin…
Browse files Browse the repository at this point in the history
…ed (#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 91a894b.
  • Loading branch information
blainekasten committed Jul 10, 2020
1 parent 73ebb1e commit 6404fc7
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
4 changes: 2 additions & 2 deletions packages/gatsby-link/src/__tests__/index.js
Expand Up @@ -94,8 +94,8 @@ describe(`<Link />`, () => {
})

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`)

Expand Down
21 changes: 18 additions & 3 deletions packages/gatsby-link/src/index.js
Expand Up @@ -9,29 +9,44 @@ 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
}

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://`) &&
!path.startsWith(`https://`) &&
!path.startsWith(`//`)

export function withAssetPrefix(path) {
return withPrefix(path, __PATH_PREFIX__)
return withPrefix(path, getGlobalPathPrefix())
}

function absolutify(path, current) {
Expand Down

0 comments on commit 6404fc7

Please sign in to comment.