diff --git a/packages/gatsby-plugin-google-tagmanager/src/__tests__/gatsby-browser.js b/packages/gatsby-plugin-google-tagmanager/src/__tests__/gatsby-browser.js new file mode 100644 index 0000000000000..42cc93606e2bf --- /dev/null +++ b/packages/gatsby-plugin-google-tagmanager/src/__tests__/gatsby-browser.js @@ -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) + }) +}) diff --git a/packages/gatsby-plugin-google-tagmanager/src/gatsby-browser.js b/packages/gatsby-plugin-google-tagmanager/src/gatsby-browser.js index 43c1e53c58294..cce321c7ce13f 100644 --- a/packages/gatsby-plugin-google-tagmanager/src/gatsby-browser.js +++ b/packages/gatsby-plugin-google-tagmanager/src/gatsby-browser.js @@ -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) + } }