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-plugin-google-tagmanager): guard against dataLayer being undefined in development #14437

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
const getAPI = setup => {
if (setup) {
setup()
}

jest.resetModules()

return require(`../gatsby-browser`)
}

beforeEach(() => {
window.dataLayer = []
jest.useFakeTimers()
process.env.NODE_ENV = undefined
})

describe(`onRouteUpdate`, () => {
it(`does not register if NODE_ENV is not production`, () => {
const { onRouteUpdate } = getAPI(() => {
process.env.NODE_ENV = `development`
})

onRouteUpdate({}, {})

jest.runAllTimers()

expect(window.dataLayer).toHaveLength(0)
})

it(`registers a route change event`, () => {
const { onRouteUpdate } = getAPI(() => {
process.env.NODE_ENV = `production`
})

onRouteUpdate({}, {})

jest.runAllTimers()

expect(window.dataLayer).toEqual([
{
event: `gatsby-route-change`,
},
])
})

it(`registers if NODE_ENV is production`, () => {
const { onRouteUpdate } = getAPI(() => {
process.env.NODE_ENV = `production`
})

onRouteUpdate({}, {})

jest.runAllTimers()

expect(window.dataLayer).toHaveLength(1)
})

it(`registers if includeInDevelopment is true`, () => {
const { onRouteUpdate } = getAPI(() => {})

onRouteUpdate(
{},
{
includeInDevelopment: true,
}
)

jest.runAllTimers()

expect(window.dataLayer).toHaveLength(1)
})
})
15 changes: 10 additions & 5 deletions packages/gatsby-plugin-google-tagmanager/src/gatsby-browser.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
exports.onRouteUpdate = ({ location }) => {
// wrap inside a timeout to ensure the title has properly been changed
setTimeout(() => {
window.dataLayer.push({ event: `gatsby-route-change` })
}, 50)
exports.onRouteUpdate = (_, pluginOptions) => {
if (
process.env.NODE_ENV === `production` ||
pluginOptions.includeInDevelopment
) {
// wrap inside a timeout to ensure the title has properly been changed
setTimeout(() => {
window.dataLayer.push({ event: `gatsby-route-change` })
}, 50)
}
}