Skip to content

Commit

Permalink
fix(gatsby-link): Do not crash in unit tests when globals are undefined
Browse files Browse the repository at this point in the history
  • Loading branch information
blainekasten committed Jul 8, 2020
1 parent 44d0c2a commit 0d1948d
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
4 changes: 2 additions & 2 deletions packages/gatsby-link/src/__tests__/index.js
Original file line number Diff line number Diff line change
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
15 changes: 12 additions & 3 deletions packages/gatsby-link/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,21 @@ export { parsePath }

const isAbsolutePath = path => path?.startsWith(`/`)

export function withPrefix(path, prefix = __BASE_PATH__) {
export function withPrefix(
path,
prefix = typeof __BASE_PATH__ !== `undefined` ? __BASE_PATH__ : undefined
) {
if (!isLocalLink(path)) {
return path
}

if (path.startsWith(`./`) || path.startsWith(`../`)) {
return path
}
const base = prefix ?? __PATH_PREFIX__ ?? `/`
const base =
prefix ??
(typeof __PATH_PREFIX__ !== `undefined` ? __PATH_PREFIX__ : `/`) ??
`/`

return `${base?.endsWith(`/`) ? base.slice(0, -1) : base}${
path.startsWith(`/`) ? path : `/${path}`
Expand All @@ -31,7 +37,10 @@ const isLocalLink = path =>
!path.startsWith(`//`)

export function withAssetPrefix(path) {
return withPrefix(path, __PATH_PREFIX__)
return withPrefix(
path,
typeof __PATH_PREFIX__ !== `undefined` ? __PATH_PREFIX__ : undefined
)
}

function absolutify(path, current) {
Expand Down

0 comments on commit 0d1948d

Please sign in to comment.