Skip to content

Commit

Permalink
fix(gatsby-plugin-google-tagmanager): guard against dataLayer being u…
Browse files Browse the repository at this point in the history
…ndefined in development (#14437)

* gatsby-plugin-google-tagmanager - Resolve #14424

* test: add some unit tests validating the functionality
  • Loading branch information
zslabs authored and DSchau committed May 30, 2019
1 parent adaabf6 commit ecb5d7b
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 5 deletions.
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)
}
}

0 comments on commit ecb5d7b

Please sign in to comment.