Skip to content

Commit 26fb722

Browse files
Added test case file: consent-tools-vanilla-opt-in.test.ts
1 parent aa86141 commit 26fb722

File tree

10 files changed

+234
-94
lines changed

10 files changed

+234
-94
lines changed

packages/consent/consent-tools-integration-tests/package.json

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,18 @@
1010
"lint": "yarn concurrently 'yarn:eslint .' 'yarn:tsc --noEmit'",
1111
"eslint": "yarn run -T eslint",
1212
"tsc": "tsc",
13-
"concurrently": "yarn run -T concurrently --raw"
13+
"concurrently": "yarn run -T concurrently --raw",
14+
"playwright-test": "playwright test",
15+
"playwright-test:headed": "playwright test --headed",
16+
"playwright-test:debug": "playwright test --debug",
17+
"serve": "http-server public -p 4567"
1418
},
1519
"installConfig": {
1620
"hoistingLimits": "workspaces"
1721
},
1822
"devDependencies": {
1923
"@internal/test-helpers": "workspace:^",
24+
"@playwright/test": "^1.28.1",
2025
"@segment/analytics-consent-tools": "workspace:^",
2126
"@segment/analytics-consent-wrapper-onetrust": "workspace:^",
2227
"@segment/analytics-next": "workspace:^",
@@ -29,6 +34,7 @@
2934
"@wdio/types": "8",
3035
"expect": "^29.4.1",
3136
"globby": "^11.0.2",
37+
"http-server": "14.1.1",
3238
"wdio-intercept-service": "^4.4.0",
3339
"webpack": "^5.94.0",
3440
"webpack-cli": "^4.8.0"
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import type { PlaywrightTestConfig } from '@playwright/test'
2+
3+
const PORT = 4567
4+
const config: PlaywrightTestConfig = {
5+
testDir: './src/playwright/tests',
6+
timeout: 30000,
7+
retries: 2,
8+
webServer: {
9+
command: 'yarn http-server public -p 4567',
10+
port: 4567,
11+
reuseExistingServer: !process.env.CI,
12+
},
13+
use: {
14+
headless: true,
15+
viewport: { width: 1280, height: 720 },
16+
baseURL: `http://localhost:${PORT}`,
17+
},
18+
}
19+
20+
export default config

packages/consent/consent-tools-integration-tests/public/consent-tools-vanilla-opt-in.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
<h1>Hello World - Serving Analytics</h1>
66
<h2>Please Check Network tab</h2>
77
<p>This page can used as playground or run by webdriver.io</p>
8-
<script src="/public/dist/consent-tools-vanilla-opt-in.bundle.js"></script>
8+
<script src="dist/consent-tools-vanilla-opt-in.bundle.js"></script>
99
</body>
1010

1111
</html>

packages/consent/consent-tools-integration-tests/public/onetrust.html

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,10 +60,10 @@
6060
n.parentNode.insertBefore(t, n)
6161
analytics._loadOptions = e
6262
}
63-
analytics._writeKey = 'foo'
63+
analytics._writeKey = 'C8qe7TaOyZburANuEAbA4WovdITZHywg'
6464
analytics.SNIPPET_VERSION = '4.15.3'
6565

66-
withOneTrust(analytics).load('foo') // modified
66+
withOneTrust(analytics).load('C8qe7TaOyZburANuEAbA4WovdITZHywg') // modified
6767
analytics.page()
6868
}
6969
})()

packages/consent/consent-tools-integration-tests/src/page-bundles/consent-tools-vanilla-opt-in/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,5 +10,5 @@ const analytics = new AnalyticsBrowser()
1010
;(window as any).analytics = analytics
1111

1212
withMockCMP(analytics).load({
13-
writeKey: 'foo',
13+
writeKey: 'C8qe7TaOyZburANuEAbA4WovdITZHywg',
1414
})
Lines changed: 73 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -1,124 +1,116 @@
1-
import { CDNSettingsBuilder } from '@internal/test-helpers'
2-
import type { SegmentEvent } from '@segment/analytics-next'
3-
import assert from 'assert'
4-
import type { Matches } from 'webdriverio'
5-
6-
const waitUntilReady = () =>
7-
browser.waitUntil(
8-
() => browser.execute(() => document.readyState === 'complete'),
9-
{
10-
timeout: 10000,
11-
}
12-
)
1+
import { Page, Route, Request } from '@playwright/test'
132

143
export abstract class BasePage {
15-
constructor(protected page: string) {}
4+
protected page: Page
5+
protected pageFile: string
6+
7+
segmentTrackingApiReqs: any[] = []
8+
fetchIntegrationReqs: any[] = []
169

17-
segmentTrackingApiReqs: Matches[] = []
18-
fetchIntegrationReqs: Matches[] = []
10+
constructor(page: Page, pageFile: string) {
11+
this.page = page
12+
this.pageFile = pageFile
13+
}
1914

2015
async load(): Promise<void> {
21-
const baseURL = browser.options.baseUrl
22-
assert(baseURL)
2316
await this.mockAPIs()
24-
await browser.url(baseURL + '/public/' + this.page)
25-
await waitUntilReady()
17+
await this.page.goto(`/${this.pageFile}`)
18+
await this.page.waitForLoadState('load')
2619
}
2720

2821
async clearStorage() {
29-
await browser.deleteAllCookies()
30-
await browser.execute(() => window.localStorage.clear())
22+
await this.page.context().clearCookies()
23+
await this.page.evaluate(() => {
24+
window.localStorage.clear()
25+
window.sessionStorage.clear()
26+
})
3127
}
3228

33-
getAllTrackingEvents(): SegmentEvent[] {
34-
const reqBodies = this.segmentTrackingApiReqs.map((el) =>
35-
JSON.parse(el.postData!)
36-
)
37-
return reqBodies
29+
async cleanup() {
30+
this.segmentTrackingApiReqs = []
31+
this.fetchIntegrationReqs = []
32+
await this.clearStorage()
33+
}
34+
35+
getAllTrackingEvents(): any[] {
36+
return this.segmentTrackingApiReqs
3837
}
3938

40-
getConsentChangedEvents(): SegmentEvent[] {
41-
const reqBodies = this.getAllTrackingEvents()
42-
const consentEvents = reqBodies.filter(
39+
getConsentChangedEvents(): any[] {
40+
return this.getAllTrackingEvents().filter(
4341
(el) => el.event === 'Segment Consent Preference Updated'
4442
)
45-
return consentEvents
4643
}
4744

48-
async cleanup() {
49-
this.segmentTrackingApiReqs = []
50-
this.fetchIntegrationReqs = []
51-
await this.clearStorage()
45+
get fetchIntegrationReqsData(): any[] {
46+
return this.fetchIntegrationReqs
5247
}
5348

54-
async mockAPIs() {
49+
private async mockAPIs() {
5550
await this.mockSegmentTrackingAPI()
5651
await this.mockCDNSettingsAPI()
5752
await this.mockNextIntegrationsAPI()
5853
}
5954

60-
private async mockSegmentTrackingAPI(): Promise<void> {
61-
const mock = await browser.mock('https://api.segment.io/v1/t', {
62-
method: 'post',
63-
})
64-
mock.respond((mock) => {
65-
this.segmentTrackingApiReqs.push(mock)
66-
// response with status 200
67-
return Promise.resolve({
68-
statusCode: 200,
69-
body: JSON.stringify({ success: true }),
70-
})
71-
})
55+
private async mockSegmentTrackingAPI() {
56+
await this.page.route(
57+
'https://api.segment.io/v1/t',
58+
async (route: Route, request: Request) => {
59+
const postData = await request.postData()
60+
const parsed = JSON.parse(postData || '{}')
61+
this.segmentTrackingApiReqs.push(parsed) // store the parsed event object directly
62+
63+
await route.fulfill({
64+
status: 200,
65+
contentType: 'application/json',
66+
body: JSON.stringify({ success: true }),
67+
})
68+
}
69+
)
7270
}
7371

74-
private async mockNextIntegrationsAPI(): Promise<void> {
75-
const mock = await browser.mock('**/next-integrations/**')
76-
mock.respond((mock) => {
77-
this.fetchIntegrationReqs.push(mock)
78-
return Promise.resolve({
79-
statusCode: 200,
80-
body: 'console.log("mocking action and classic destinations")',
81-
})
82-
})
72+
private async mockNextIntegrationsAPI() {
73+
await this.page.route(
74+
'**/next-integrations/**',
75+
async (route: Route, request: Request) => {
76+
this.fetchIntegrationReqs.push({ url: request.url() })
77+
await route.fulfill({
78+
status: 200,
79+
body: 'console.log("mocking action and classic destinations")',
80+
contentType: 'application/javascript',
81+
})
82+
}
83+
)
8384
}
8485

85-
/** * Mock the CDN Settings endpoint so that this can run offline
86-
*/
87-
private async mockCDNSettingsAPI(): Promise<void> {
88-
const settings = new CDNSettingsBuilder({
89-
writeKey: 'something',
90-
})
91-
.addActionDestinationSettings(
92-
{
86+
private async mockCDNSettingsAPI() {
87+
const settings = {
88+
integrations: {
89+
FullStory: {
9390
url: 'https://cdn.segment.com/next-integrations/actions/fullstory-plugins/foo.js',
94-
creationName: 'FullStory',
9591
consentSettings: {
9692
categories: ['FooCategory2'],
9793
},
9894
},
99-
{
95+
'Actions Amplitude': {
10096
url: 'https://cdn.segment.com/next-integrations/actions/amplitude-plugins/foo.js',
101-
creationName: 'Actions Amplitude',
10297
consentSettings: {
10398
categories: ['FooCategory1'],
10499
},
105-
}
106-
)
107-
.build()
108-
109-
const mock = await browser.mock('**/settings')
110-
mock.respond(settings, {
111-
statusCode: 200,
112-
headers: {
113-
'Content-Type': 'application/json',
100+
},
114101
},
102+
}
103+
104+
await this.page.route('**/settings', async (route: Route) => {
105+
await route.fulfill({
106+
status: 200,
107+
contentType: 'application/json',
108+
body: JSON.stringify(settings),
109+
})
115110
})
116111
}
117112

118-
/**
119-
* Hard reload the page
120-
*/
121-
reload() {
122-
return browser.execute(() => window.location.reload())
113+
async reload() {
114+
await this.page.reload()
123115
}
124116
}
Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,28 @@
1+
import { Page } from '@playwright/test'
12
import { BasePage } from './base-page'
23

34
export class ConsentToolsVanilla extends BasePage {
5+
constructor(page: Page, file: string) {
6+
super(page, file)
7+
}
8+
49
async clickGiveConsent() {
5-
const button = await $('#give-consent')
6-
return button.click()
10+
await this.page.locator('#give-consent').click()
711
}
12+
813
async clickDenyConsent() {
9-
const button = await $('#give-consent')
10-
return button.click()
14+
await this.page.locator('#deny-consent').click()
1115
}
1216
}
1317

1418
export class ConsentToolsVanillaOptOut extends ConsentToolsVanilla {
15-
constructor() {
16-
super('consent-tools-vanilla-opt-out.html')
19+
constructor(page: Page) {
20+
super(page, 'consent-tools-vanilla-opt-out.html')
1721
}
1822
}
1923

2024
export class ConsentToolsVanillaOptIn extends ConsentToolsVanilla {
21-
constructor() {
22-
super('consent-tools-vanilla-opt-in.html')
25+
constructor(page: Page) {
26+
super(page, 'consent-tools-vanilla-opt-in.html')
2327
}
2428
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import { test, expect } from '@playwright/test'
2+
3+
test('Homepage has welcome message', async ({ page }) => {
4+
await page.goto('https://www.example.com/')
5+
await expect(page.locator('text=Example Domain')).toBeVisible()
6+
})
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import type { Reporter } from '@playwright/test/types/testReporter'
2+
import type { TestCase } from '@playwright/test/types/testReporter'
3+
import type { TestResult } from '@playwright/test/types/testReporter'
4+
5+
class PlaywrightLogger implements Reporter {
6+
onTestEnd(test: TestCase, result: TestResult): void {
7+
const passed = result.status === 'passed'
8+
console.log(
9+
[
10+
`${passed ? '✅ Passed' : '❌ Failed'}! ${test.title}`,
11+
test.location.file,
12+
!passed && result.error ? result.error.message : '',
13+
].join('\n')
14+
)
15+
}
16+
}
17+
18+
export default PlaywrightLogger

0 commit comments

Comments
 (0)