Skip to content

Commit

Permalink
Add gtag id only in prod (#3258)
Browse files Browse the repository at this point in the history
* Add gtag id only in prod

* Create gtag.spec.ts

* Base gtag tests on fixture to run in prod or other envs
  • Loading branch information
clari182 authored Dec 6, 2024
1 parent c369085 commit 4e271d0
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 1 deletion.
8 changes: 7 additions & 1 deletion site/gatsby-site/gatsby-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ cloudinary.config({ cloud_name: config.cloudinary.cloudName });

const adapter = require('gatsby-adapter-netlify').default;

let googleTrackingIds = [];

if (process.env.SITE_URL === config.gatsby.siteUrl) {
googleTrackingIds.push(config.gatsby.gaTrackingId);
}

const plugins = [
'layout',
{
Expand Down Expand Up @@ -65,7 +71,7 @@ const plugins = [
{
resolve: `gatsby-plugin-google-gtag`,
options: {
trackingIds: [config.gatsby.gaTrackingId],
trackingIds: googleTrackingIds,
},
},
{
Expand Down
2 changes: 2 additions & 0 deletions site/gatsby-site/playwright/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ type ConfigType = {
IS_EMPTY_ENVIRONMENT: string;
AVAILABLE_LANGUAGES?: string;
[key: string]: string;
SITE_URL?: string;
};

const config: ConfigType = {
E2E_ADMIN_PASSWORD: process.env.E2E_ADMIN_PASSWORD!,
E2E_ADMIN_USERNAME: process.env.E2E_ADMIN_USERNAME!,
IS_EMPTY_ENVIRONMENT: process.env.IS_EMPTY_ENVIRONMENT ?? '',
AVAILABLE_LANGUAGES: process.env.GATSBY_AVAILABLE_LANGUAGES ?? '',
SITE_URL: process.env.SITE_URL ?? '',
}

Object.keys(config).forEach((key) => {
Expand Down
40 changes: 40 additions & 0 deletions site/gatsby-site/playwright/e2e/unit/gtag.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { expect } from '@playwright/test';
import config from '../../../config';
import { test } from '../../utils';

const googleTrackingId = config.gatsby.gaTrackingId;

test.describe('Google Analytics Tracking', () => {
test('Should track gtag only on production', async ({ page, runOnlyInProduction }) => {
await page.goto('/');

const hasGoogleTracking = await page.locator(`script[src*="https://www.googletagmanager.com/gtag/js?id=${googleTrackingId}"]`).count();

expect(hasGoogleTracking).toBeGreaterThan(0);

const [trackingRequest] = await Promise.all([
page.waitForRequest((request) => request.url().includes(`https://www.google-analytics.com`) && request.method() === 'POST'),

]);

expect(trackingRequest).toBeTruthy();
});


test('Should not track gtag outside production', async ({ page, runAnywhereExceptProduction }) => {
await page.goto('/');

const hasGoogleTracking = await page.locator(`script[src*="https://www.googletagmanager.com/gtag/js?id=${googleTrackingId}"]`).count();
expect(hasGoogleTracking).toBe(0);

let trackingRequestMade = false;
page.on('request', (request) => {
if (request.url().includes(`https://www.google-analytics.com`) && request.method() === 'POST') {
trackingRequestMade = true;
}
});

await page.reload();
expect(trackingRequestMade).toBe(false);
});
});
19 changes: 19 additions & 0 deletions site/gatsby-site/playwright/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import assert from 'node:assert';
import fs from 'fs';
import path from 'path';
import * as memoryMongo from './memory-mongo';
import siteConfig from '../config';

declare module '@playwright/test' {
interface Request {
Expand All @@ -20,6 +21,8 @@ type TestFixtures = {
runOnlyOnEmptyEnvironment: () => Promise<void>,
login: (username: string, password: string, options?: { customData?: Record<string, unknown> }) => Promise<string[]>,
retryDelay?: [({ }: {}, use: () => Promise<void>, testInfo: { retry: number }) => Promise<void>, { auto: true }],
runOnlyInProduction: () => Promise<void>,
runAnywhereExceptProduction: () => Promise<void>,
};

const getUserIdFromLocalStorage = async (page: Page) => {
Expand Down Expand Up @@ -117,6 +120,22 @@ export const test = base.extend<TestFixtures>({

await use();
}, { auto: true }],

runOnlyInProduction: async ({ }, use, testInfo) => {
if (config.SITE_URL !== siteConfig.gatsby.siteUrl) {
testInfo.skip();
}

await use(null);
},

runAnywhereExceptProduction: async ({ }, use, testInfo) => {
if (config.SITE_URL === siteConfig.gatsby.siteUrl) {
testInfo.skip();
}

await use(null);
}
});

// SEE: https://playwright.dev/docs/api/class-page#page-wait-for-request
Expand Down

0 comments on commit 4e271d0

Please sign in to comment.