Skip to content

Commit

Permalink
fix: take into account router.base when reporting page tracking event
Browse files Browse the repository at this point in the history
 - include router's base in `pageUrl` property of triggered page tracking events
 - replace head function in example nuxt.config.js with a plain object
   as that has triggered a noisy warning and wasn't tested anyway
 - add @types/jest to provide completions for test functions (when using
   relevant language server).
  • Loading branch information
rchl committed Mar 17, 2020
1 parent c062258 commit a251bf7
Show file tree
Hide file tree
Showing 6 changed files with 96 additions and 9 deletions.
6 changes: 2 additions & 4 deletions example/nuxt.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,8 @@ const { resolve } = require('path')
module.exports = {
rootDir: resolve(__dirname, '..'),
buildDir: resolve(__dirname, '.nuxt'),
head () {
return {
title: '@nuxtjs/gtm-module'
}
head: {
title: '@nuxtjs/gtm-module'
},
srcDir: __dirname,
render: {
Expand Down
6 changes: 5 additions & 1 deletion lib/module.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,13 +78,17 @@ module.exports = async function gtmModule (_options) {
this.options.head.__dangerouslyDisableSanitizersByTagID[options.scriptId] = ['innerHTML']
this.options.head.__dangerouslyDisableSanitizersByTagID[options.noscriptId] = ['innerHTML']

// Remove trailing slash to avoid duplicate slashes when appending route path
const routerBase = this.options.router.base.replace(/\/+$/, '')

// Register plugin
this.addPlugin({
src: path.resolve(__dirname, 'plugin.js'),
fileName: 'gtm.js',
options: {
...options,
renderIframe
renderIframe,
routerBase
}
})
}
Expand Down
8 changes: 4 additions & 4 deletions lib/plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,11 @@ function startPageTracking(ctx) {
ctx.$gtm.push(to.gtm || {
routeName: to.name,
pageType: 'PageView',
pageUrl: to.fullPath,
pageTitle: (typeof document !== 'undefined' && document.title) || '',
pageUrl: '<%= options.routerBase %>' + to.fullPath,
pageTitle: (typeof document !== 'undefined' && document.title) || '',
event: '<%= options.pageViewEventName %>'
})
}, 250)
})
}, 250)
})
}

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"@commitlint/config-conventional": "latest",
"@nuxtjs/eslint-config": "latest",
"@nuxtjs/module-test-utils": "latest",
"@types/jest": "latest",
"babel-eslint": "latest",
"babel-jest": "latest",
"codecov": "latest",
Expand Down
76 changes: 76 additions & 0 deletions test/module.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,21 @@ const path = require('path')
const { setup, loadConfig, get, url } = require('@nuxtjs/module-test-utils')
const defaultSettings = require(path.join(__dirname, '../', 'lib', 'defaults.js'))

function expectPageTrackingEvent (eventsArray, expectedEvent) {
return new Promise((resolve) => {
// Need to wait at least 250ms as that's how long plugin delays before triggering event.
setTimeout(() => {
expect(eventsArray).toStrictEqual(
expect.arrayContaining([
expect.objectContaining(expectedEvent)
])
)
expect(eventsArray.filter(event => event.event === 'nuxtRoute').length).toBe(1)
resolve()
}, 300)
})
}

const modes = ['universal', 'spa']

for (const mode of modes) {
Expand Down Expand Up @@ -54,5 +69,66 @@ for (const mode of modes) {

expect(totalAmoutOfGtmScriptsAtHead).toBeLessThan(3)
})

test('Should include pushed event', async () => {
const window = await nuxt.renderAndGetWindow(url('/'))
expect(window.dataLayer).toStrictEqual(
expect.arrayContaining([
expect.objectContaining({ event: 'ssr' })
])
)
expect(window.dataLayer.filter(event => event.event === 'ssr').length).toBe(1)
})

test('Should include page tracking event', async () => {
const window = await nuxt.renderAndGetWindow(url('/'))

await expectPageTrackingEvent(window.dataLayer, {
event: 'nuxtRoute',
pageTitle: '@nuxtjs/gtm-module',
pageType: 'PageView',
pageUrl: '/',
routeName: 'index'
})
})
})
}

for (const mode of modes) {
describe(`Page tracking with router base (${mode} mode)`, () => {
let nuxt

const override = {
gtm: {
layer: 'testDataLayer',
pageTracking: true
}
}

const nuxtConfig = loadConfig(__dirname, '../../example', override, { merge: true })
if (!nuxtConfig.router) {
nuxtConfig.router = {}
}
nuxtConfig.router.base = '/base/'

beforeAll(async () => {
({ nuxt } = (await setup(nuxtConfig)))
}, 60000)

afterAll(async () => {
await nuxt.close()
})

test('Event should contain page URL with base', async () => {
const window = await nuxt.renderAndGetWindow(url('/base/'))

await expectPageTrackingEvent(window.testDataLayer, {
event: 'nuxtRoute',
pageTitle: '@nuxtjs/gtm-module',
pageType: 'PageView',
pageUrl: '/base/',
routeName: 'index'
})
})
})
}
8 changes: 8 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1456,6 +1456,14 @@
"@types/istanbul-lib-coverage" "*"
"@types/istanbul-lib-report" "*"

"@types/jest@latest":
version "25.1.4"
resolved "https://registry.yarnpkg.com/@types/jest/-/jest-25.1.4.tgz#9e9f1e59dda86d3fd56afce71d1ea1b331f6f760"
integrity sha512-QDDY2uNAhCV7TMCITrxz+MRk1EizcsevzfeS6LykIlq2V1E5oO4wXG8V2ZEd9w7Snxeeagk46YbMgZ8ESHx3sw==
dependencies:
jest-diff "^25.1.0"
pretty-format "^25.1.0"

"@types/json-schema@^7.0.3":
version "7.0.4"
resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.4.tgz#38fd73ddfd9b55abb1e1b2ed578cb55bd7b7d339"
Expand Down

0 comments on commit a251bf7

Please sign in to comment.