Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(gatsby-link): Do not crash in unit tests when globals are undefined #25608

Merged
merged 5 commits into from
Jul 10, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
13 changes: 10 additions & 3 deletions packages/gatsby-link/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,29 +9,36 @@ 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 = () =>
typeof __PATH_PREFIX__ !== `undefined` ? __PATH_PREFIX__ : undefined
const getGlobalBasePrefix = () =>
typeof __BASE_PATH__ !== `undefined` ? __BASE_PATH__ : undefined

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