Skip to content

Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.

Average Scroll Depth Metric: Track custom props on pageleaves (#4964)

RobertJoonasf262bea316bb
diff --git a/test/plausible_web/controllers/api/external_controller_test.exs b/test/plausible_web/controllers/api/external_controller_test.exs
index fdd391ef05..27599c68f6 100644
--- a/test/plausible_web/controllers/api/external_controller_test.exs
+++ b/test/plausible_web/controllers/api/external_controller_test.exs
@@ -649,6 +649,29 @@ defmodule PlausibleWeb.Api.ExternalControllerTest do
assert Map.get(event, :"meta.value") == ["true", "12"]
end
+ test "records custom props for a pageleave event", %{conn: conn, site: site} do
+ post(conn, "/api/event", %{
+ n: "pageview",
+ u: "https://ab.cd",
+ d: site.domain
+ })
+
+ post(conn, "/api/event", %{
+ name: "pageleave",
+ url: "http://ab.cd/",
+ domain: site.domain,
+ props: %{
+ bool_test: true,
+ number_test: 12
+ }
+ })
+
+ pageleave = get_events(site) |> Enum.find(&(&1.name == "pageleave"))
+
+ assert Map.get(pageleave, :"meta.key") == ["bool_test", "number_test"]
+ assert Map.get(pageleave, :"meta.value") == ["true", "12"]
+ end
+
test "filters out bad props", %{conn: conn, site: site} do
params = %{
name: "Signup",
diff --git a/test/plausible_web/controllers/api/external_stats_controller/query_test.exs b/test/plausible_web/controllers/api/external_stats_controller/query_test.exs
index 009cec6189..1681bb208f 100644
--- a/test/plausible_web/controllers/api/external_stats_controller/query_test.exs
+++ b/test/plausible_web/controllers/api/external_stats_controller/query_test.exs
@@ -3759,6 +3759,40 @@ defmodule PlausibleWeb.Api.ExternalStatsController.QueryTest do
]
end
+ test "can query scroll_depth with page + custom prop filter", %{conn: conn, site: site} do
+ populate_stats(site, [
+ build(:pageview, user_id: 123, timestamp: ~N[2021-01-01 00:00:00]),
+ build(:pageleave, user_id: 123, timestamp: ~N[2021-01-01 00:00:10], scroll_depth: 40),
+ build(:pageview,
+ "meta.key": ["author"],
+ "meta.value": ["john"],
+ user_id: 123,
+ timestamp: ~N[2021-01-01 00:00:10]
+ ),
+ build(:pageleave,
+ "meta.key": ["author"],
+ "meta.value": ["john"],
+ user_id: 123,
+ timestamp: ~N[2021-01-01 00:00:20],
+ scroll_depth: 60
+ ),
+ build(:pageview, user_id: 456, timestamp: ~N[2021-01-01 00:00:00]),
+ build(:pageleave, user_id: 456, timestamp: ~N[2021-01-01 00:00:10], scroll_depth: 80)
+ ])
+
+ conn =
+ post(conn, "/api/v2/query-internal-test", %{
+ "site_id" => site.domain,
+ "filters" => [["is", "event:page", ["/"]], ["is", "event:props:author", ["john"]]],
+ "date_range" => "all",
+ "metrics" => ["scroll_depth"]
+ })
+
+ assert json_response(conn, 200)["results"] == [
+ %{"metrics" => [60], "dimensions" => []}
+ ]
+ end
+
test "scroll depth is 0 when no pageleave data in range", %{conn: conn, site: site} do
populate_stats(site, [
build(:pageview, timestamp: ~N[2021-01-01 00:00:00])
@@ -4048,6 +4082,78 @@ defmodule PlausibleWeb.Api.ExternalStatsController.QueryTest do
%{"dimensions" => ["/blog", "2020-01-02"], "metrics" => [20]}
]
end
+
+ test "breakdown by a custom prop with a page filter", %{conn: conn, site: site} do
+ populate_stats(site, [
+ build(:pageview, user_id: 123, timestamp: ~N[2021-01-01 00:00:00], pathname: "/blog"),
+ build(:pageleave,
+ user_id: 123,
+ timestamp: ~N[2021-01-01 00:01:00],
+ pathname: "/blog",
+ scroll_depth: 91
+ ),
+ build(:pageview,
+ user_id: 123,
+ timestamp: ~N[2021-01-01 00:02:00],
+ "meta.key": ["author"],
+ "meta.value": ["john"],
+ pathname: "/blog/john-post"
+ ),
+ build(:pageleave,
+ user_id: 123,
+ timestamp: ~N[2021-01-01 00:03:00],
+ "meta.key": ["author"],
+ "meta.value": ["john"],
+ pathname: "/blog/john-post",
+ scroll_depth: 40
+ ),
+ build(:pageview,
+ user_id: 123,
+ timestamp: ~N[2021-01-01 00:02:00],
+ "meta.key": ["author"],
+ "meta.value": ["john"],
+ pathname: "/another-blog/john-post"
+ ),
+ build(:pageleave,
+ user_id: 123,
+ timestamp: ~N[2021-01-01 00:03:00],
+ "meta.key": ["author"],
+ "meta.value": ["john"],
+ pathname: "/another-blog/john-post",
+ scroll_depth: 90
+ ),
+ build(:pageview,
+ user_id: 456,
+ timestamp: ~N[2021-01-01 00:02:00],
+ "meta.key": ["author"],
+ "meta.value": ["john"],
+ pathname: "/blog/john-post"
+ ),
+ build(:pageleave,
+ user_id: 456,
+ timestamp: ~N[2021-01-01 00:03:00],
+ "meta.key": ["author"],
+ "meta.value": ["john"],
+ pathname: "/blog/john-post",
+ scroll_depth: 46
+ )
+ ])
+
+ conn =
+ post(conn, "/api/v2/query-internal-test", %{
+ "site_id" => site.domain,
+ "metrics" => ["scroll_depth"],
+ "order_by" => [["scroll_depth", "desc"]],
+ "date_range" => "all",
+ "filters" => [["matches", "event:page", ["/blog.*"]]],
+ "dimensions" => ["event:props:author"]
+ })
+
+ assert json_response(conn, 200)["results"] == [
+ %{"dimensions" => ["(none)"], "metrics" => [91]},
+ %{"dimensions" => ["john"], "metrics" => [43]}
+ ]
+ end
end
test "can filter by utm_medium case insensitively", %{conn: conn, site: site} do
diff --git a/tracker/.eslintrc.json b/tracker/.eslintrc.json
index 582cb49260..56b2758529 100644
--- a/tracker/.eslintrc.json
+++ b/tracker/.eslintrc.json
@@ -19,8 +19,7 @@
{
"assertFunctionNames": [
"expect",
- "clickPageElementAndExpectEventRequests",
- "expectCustomEvent"
+ "expectPlausibleInAction"
]
}
]
diff --git a/tracker/src/customEvents.js b/tracker/src/customEvents.js
index 19f1d77eaf..b638b6fdd9 100644
--- a/tracker/src/customEvents.js
+++ b/tracker/src/customEvents.js
@@ -193,6 +193,8 @@ function handleTaggedElementClickEvent(event) {
var eventAttrs = getTaggedEventAttributes(taggedElement)
if (clickedLink) {
+ // if the clicked tagged element is a link, we attach the `url` property
+ // automatically for user convenience
eventAttrs.props.url = clickedLink.href
sendLinkClickEvent(event, clickedLink, eventAttrs)
} else {
diff --git a/tracker/src/plausible.js b/tracker/src/plausible.js
index 14e7bf2c7e..ad23e290b4 100644
--- a/tracker/src/plausible.js
+++ b/tracker/src/plausible.js
@@ -12,9 +12,15 @@
var endpoint = scriptEl.getAttribute('data-api') || defaultEndpoint(scriptEl)
var dataDomain = scriptEl.getAttribute('data-domain')
- function onIgnoredEvent(reason, options) {
+ function onIgnoredEvent(eventName, reason, options) {
if (reason) console.warn('Ignoring Event: ' + reason);
options && options.callback && options.callback()
+
+ {{#if pageleave}}
+ if (eventName === 'pageview') {
+ currentPageLeaveIgnored = true
+ }
+ {{/if}}
}
function defaultEndpoint(el) {
@@ -31,10 +37,9 @@
{{#if pageleave}}
// :NOTE: Tracking pageleave events is currently experimental.
- // Keeps track of the URL to be sent in the pageleave event payload.
- // Should get updated on pageviews triggered manually with a custom
- // URL, and on SPA navigation.
+ var currentPageLeaveIgnored
var currentPageLeaveURL = location.href
+ var currentPageLeaveProps = {}
// Multiple pageviews might be sent by the same script when the page
// uses client-side routing (e.g. hash or history-based). This flag
@@ -92,7 +97,7 @@
})
function triggerPageLeave() {
- if (pageLeaveSending) {return}
+ if (pageLeaveSending || currentPageLeaveIgnored) {return}
pageLeaveSending = true
setTimeout(function () {pageLeaveSending = false}, 500)
@@ -101,6 +106,7 @@
sd: Math.round((maxScrollDepthPx / currentDocumentHeight) * 100),
d: dataDomain,
u: currentPageLeaveURL,
+ p: currentPageLeaveProps
}
{{#if hash}}
@@ -126,15 +132,15 @@
{{#unless local}}
if (/^localhost$|^127(\.[0-9]+){0,2}\.[0-9]+$|^\[::1?\]$/.test(location.hostname) || location.protocol === 'file:') {
- return onIgnoredEvent('localhost', options)
+ return onIgnoredEvent(eventName, 'localhost', options)
}
if ((window._phantom || window.__nightmare || window.navigator.webdriver || window.Cypress) && !window.__plausible) {
- return onIgnoredEvent(null, options)
+ return onIgnoredEvent(eventName, null, options)
}
{{/unless}}
try {
if (window.localStorage.plausible_ignore === 'true') {
- return onIgnoredEvent('localStorage flag', options)
+ return onIgnoredEvent(eventName, 'localStorage flag', options)
}
} catch (e) {
@@ -147,7 +153,7 @@
var isIncluded = !dataIncludeAttr || (dataIncludeAttr && dataIncludeAttr.split(',').some(pathMatches))
var isExcluded = dataExcludeAttr && dataExcludeAttr.split(',').some(pathMatches)
- if (!isIncluded || isExcluded) return onIgnoredEvent('exclusion rule', options)
+ if (!isIncluded || isExcluded) return onIgnoredEvent(eventName, 'exclusion rule', options)
}
function pathMatches(wildcardPath) {
@@ -167,10 +173,6 @@
{{#if manual}}
var customURL = options && options.u
- {{#if pageleave}}
- isPageview && customURL && (currentPageLeaveURL = customURL)
- {{/if}}
-
payload.u = customURL ? customURL : location.href
{{else}}
payload.u = location.href
@@ -220,6 +222,9 @@
if (request.readyState === 4) {
{{#if pageleave}}
if (isPageview) {
+ currentPageLeaveIgnored = false
+ currentPageLeaveURL = payload.u
+ currentPageLeaveProps = payload.p
registerPageLeaveListener()
}
{{/if}}
@@ -245,7 +250,6 @@
{{#if pageleave}}
if (isSPANavigation && listeningPageLeave) {
triggerPageLeave();
- currentPageLeaveURL = location.href;
currentDocumentHeight = getDocumentHeight()
maxScrollDepthPx = getCurrentScrollDepthPx()
}
diff --git a/tracker/test/custom-event-edge-cases.spec.js b/tracker/test/custom-event-edge-cases.spec.js
index fb4b4a846c..59325de3e8 100644
--- a/tracker/test/custom-event-edge-cases.spec.js
+++ b/tracker/test/custom-event-edge-cases.spec.js
@@ -1,5 +1,5 @@
-const { mockRequest, mockManyRequests, expectCustomEvent } = require('./support/test-utils')
-const { expect, test } = require('@playwright/test')
+const { expectPlausibleInAction } = require('./support/test-utils')
+const { test } = require('@playwright/test')
const { LOCAL_SERVER_ADDR } = require('./support/server')
test.describe('script.file-downloads.outbound-links.tagged-events.js', () => {
@@ -7,32 +7,30 @@ test.describe('script.file-downloads.outbound-links.tagged-events.js', () => {
await page.goto('/custom-event-edge-case.html')
const downloadURL = await page.locator('#outbound-download-link').getAttribute('href')
- const plausibleRequestMockList = mockManyRequests(page, '/api/event', 2)
- await page.click('#outbound-download-link')
-
- const requests = await plausibleRequestMockList
- expect(requests.length).toBe(1)
- expectCustomEvent(requests[0], 'Outbound Link: Click', {url: downloadURL})
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#outbound-download-link'),
+ expectedRequests: [{n: 'Outbound Link: Click', p: {url: downloadURL}}]
+ })
})
test('sends file download event when local download link clicked', async ({ page }) => {
await page.goto('/custom-event-edge-case.html')
const downloadURL = LOCAL_SERVER_ADDR + '/' + await page.locator('#local-download').getAttribute('href')
- const plausibleRequestMock = mockRequest(page, '/api/event')
- await page.click('#local-download')
-
- expectCustomEvent(await plausibleRequestMock, 'File Download', {url: downloadURL})
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#local-download'),
+ expectedRequests: [{n: 'File Download', p: {url: downloadURL}}]
+ })
})
test('sends only tagged event when clicked link is tagged + outbound + download', async ({ page }) => {
await page.goto('/custom-event-edge-case.html')
- const plausibleRequestMockList = mockManyRequests(page, '/api/event', 3)
- await page.click('#tagged-outbound-download-link')
-
- const requests = await plausibleRequestMockList
- expect(requests.length).toBe(1)
- expectCustomEvent(requests[0], 'Foo', {})
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#tagged-outbound-download-link'),
+ expectedRequests: [{n: 'Foo', p: {url: 'https://awesome.website.com/file.pdf'}}],
+ awaitedRequestCount: 3,
+ expectedRequestCount: 1
+ })
})
})
diff --git a/tracker/test/file-downloads.spec.js b/tracker/test/file-downloads.spec.js
index 0b353e8df5..5bac615d3b 100644
--- a/tracker/test/file-downloads.spec.js
+++ b/tracker/test/file-downloads.spec.js
@@ -1,4 +1,4 @@
-const { mockRequest, expectCustomEvent, mockManyRequests, metaKey } = require('./support/test-utils')
+const { mockRequest, mockManyRequests, metaKey, expectPlausibleInAction } = require('./support/test-utils')
const { expect, test } = require('@playwright/test')
const { LOCAL_SERVER_ADDR } = require('./support/server')
@@ -7,11 +7,13 @@ test.describe('file-downloads extension', () => {
await page.goto('/file-download.html')
const downloadURL = await page.locator('#link').getAttribute('href')
- const plausibleRequestMock = mockRequest(page, '/api/event')
const downloadRequestMock = mockRequest(page, downloadURL)
- await page.click('#link', { modifiers: [metaKey()] })
- expectCustomEvent(await plausibleRequestMock, 'File Download', { url: downloadURL })
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#link', { modifiers: [metaKey()] }),
+ expectedRequests: [{n: 'File Download', p: { url: downloadURL }}]
+ })
+
expect(await downloadRequestMock, "should not make download request").toBeNull()
})
@@ -19,11 +21,13 @@ test.describe('file-downloads extension', () => {
await page.goto('/file-download.html')
const downloadURL = await page.locator('#link').getAttribute('href')
- const plausibleRequestMock = mockRequest(page, '/api/event')
const downloadRequestMock = mockRequest(page, downloadURL)
- await page.click('#link-child')
- expectCustomEvent(await plausibleRequestMock, 'File Download', { url: downloadURL })
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#link-child'),
+ expectedRequests: [{n: 'File Download', p: { url: downloadURL }}]
+ })
+
expect((await downloadRequestMock).url()).toContain(downloadURL)
})
@@ -31,11 +35,10 @@ test.describe('file-downloads extension', () => {
await page.goto('/file-download.html')
const downloadURL = await page.locator('#link-query').getAttribute('href')
- const plausibleRequestMock = mockRequest(page, '/api/event')
- await page.click('#link-query')
-
- const expectedURL = downloadURL.split("?")[0]
- expectCustomEvent(await plausibleRequestMock, 'File Download', { url: expectedURL })
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#link-query'),
+ expectedRequests: [{n: 'File Download', p: { url: downloadURL.split("?")[0] }}]
+ })
})
test('starts download only once', async ({ page }) => {
diff --git a/tracker/test/fixtures/pageleave-hash-pageview-props.html b/tracker/test/fixtures/pageleave-hash-pageview-props.html
new file mode 100644
index 0000000000..651acdb034
--- /dev/null
+++ b/tracker/test/fixtures/pageleave-hash-pageview-props.html
@@ -0,0 +1,36 @@
+<!DOCTYPE html>
+<html lang="en">
+
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <meta http-equiv="X-UA-Compatible" content="ie=edge">
+ <title>Plausible Playwright tests</title>
+ <script id="plausible-script" defer src="/tracker/js/plausible.hash.local.pageleave.pageview-props.js"></script>
+</head>
+
+<body>
+ <h1>Blog</h1>
+
+ <button id="home" onclick="goHome()">Home</button>
+ <button id="john-post" onclick="goToBlogPost('john')">A blog post of John</button>
+ <button id="jane-post" onclick="goToBlogPost('jane')">A blog post of Jane</button>
+
+ <div id="content"></div>
+
+ <script>
+ function goToBlogPost(author) {
+ document.getElementById('plausible-script').setAttribute('event-author', author)
+ window.location.hash = `/${author}-post`
+ document.getElementById('content').innerHTML = `Hello, I'm ${author} and this is my post.`
+ }
+
+ function goHome() {
+ document.getElementById('plausible-script').removeAttribute('event-author')
+ window.location.hash = ''
+ document.getElementById('content').innerHTML = ''
+ }
+ </script>
+</body>
+
+</html>
diff --git a/tracker/test/fixtures/pageleave-manual.html b/tracker/test/fixtures/pageleave-manual.html
index 6fa3fd5423..f87f00b322 100644
--- a/tracker/test/fixtures/pageleave-manual.html
+++ b/tracker/test/fixtures/pageleave-manual.html
@@ -16,11 +16,16 @@
<button id="pageview-trigger-custom-url">
Triggers a pageview with custom URL
</button>
+ <button id="pageview-trigger-custom-props">
+ Triggers a pageview with custom props
+ </button>
<script>
document.addEventListener('click', (e) => {
if (e.target.id === 'pageview-trigger-custom-url') {
window.plausible('pageview', {u: 'https://example.com/custom/location'})
+ } else if (e.target.id === 'pageview-trigger-custom-props') {
+ window.plausible('pageview', {props: {author: 'John'}})
}
})
</script>
diff --git a/tracker/test/fixtures/pageleave-pageview-props.html b/tracker/test/fixtures/pageleave-pageview-props.html
new file mode 100644
index 0000000000..51aee537ed
--- /dev/null
+++ b/tracker/test/fixtures/pageleave-pageview-props.html
@@ -0,0 +1,16 @@
+<!DOCTYPE html>
+<html lang="en">
+
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <meta http-equiv="X-UA-Compatible" content="ie=edge">
+ <title>Plausible Playwright tests</title>
+ <script defer event-author="John" src="/tracker/js/plausible.local.pageleave.pageview-props.js"></script>
+</head>
+
+<body>
+ <a id="navigate-away" href="/manual.html">Navigate away</a>
+</body>
+
+</html>
diff --git a/tracker/test/manual.spec.js b/tracker/test/manual.spec.js
index 8ab8d9d731..c931ceb895 100644
--- a/tracker/test/manual.spec.js
+++ b/tracker/test/manual.spec.js
@@ -1,4 +1,4 @@
-const { clickPageElementAndExpectEventRequests } = require('./support/test-utils')
+const { expectPlausibleInAction } = require('./support/test-utils')
const { test } = require('@playwright/test')
const { LOCAL_SERVER_ADDR } = require('./support/server')
@@ -6,28 +6,34 @@ test.describe('manual extension', () => {
test('can trigger custom events with and without a custom URL if pageview was sent with the default URL', async ({ page }) => {
await page.goto('/manual.html')
- await clickPageElementAndExpectEventRequests(page, '#pageview-trigger', [
- {n: 'pageview', u: `${LOCAL_SERVER_ADDR}/manual.html`}
- ])
- await clickPageElementAndExpectEventRequests(page, '#custom-event-trigger', [
- {n: 'CustomEvent', u: `${LOCAL_SERVER_ADDR}/manual.html`}
- ])
- await clickPageElementAndExpectEventRequests(page, '#custom-event-trigger-custom-url', [
- {n: 'CustomEvent', u: `https://example.com/custom/location`}
- ])
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#pageview-trigger'),
+ expectedRequests: [{n: 'pageview', u: `${LOCAL_SERVER_ADDR}/manual.html`}]
+ })
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#custom-event-trigger'),
+ expectedRequests: [{n: 'CustomEvent', u: `${LOCAL_SERVER_ADDR}/manual.html`}]
+ })
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#custom-event-trigger-custom-url'),
+ expectedRequests: [{n: 'CustomEvent', u: `https://example.com/custom/location`}]
+ })
})
test('can trigger custom events with and without a custom URL if pageview was sent with a custom URL', async ({ page }) => {
await page.goto('/manual.html')
- await clickPageElementAndExpectEventRequests(page, '#pageview-trigger-custom-url', [
- {n: 'pageview', u: `https://example.com/custom/location`}
- ])
- await clickPageElementAndExpectEventRequests(page, '#custom-event-trigger', [
- {n: 'CustomEvent', u: `${LOCAL_SERVER_ADDR}/manual.html`}
- ])
- await clickPageElementAndExpectEventRequests(page, '#custom-event-trigger-custom-url', [
- {n: 'CustomEvent', u: `https://example.com/custom/location`}
- ])
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#pageview-trigger-custom-url'),
+ expectedRequests: [{n: 'pageview', u: `https://example.com/custom/location`}]
+ })
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#custom-event-trigger'),
+ expectedRequests: [{n: 'CustomEvent', u: `${LOCAL_SERVER_ADDR}/manual.html`}]
+ })
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#custom-event-trigger-custom-url'),
+ expectedRequests: [{n: 'CustomEvent', u: `https://example.com/custom/location`}]
+ })
})
})
diff --git a/tracker/test/outbound-links.spec.js b/tracker/test/outbound-links.spec.js
index 54d8a500fc..f03fc5e395 100644
--- a/tracker/test/outbound-links.spec.js
+++ b/tracker/test/outbound-links.spec.js
@@ -1,18 +1,18 @@
-const { mockRequest, expectCustomEvent, metaKey } = require('./support/test-utils')
+const { mockRequest, metaKey, expectPlausibleInAction } = require('./support/test-utils')
const { expect, test } = require('@playwright/test')
test.describe('outbound-links extension', () => {
-
test('sends event and does not navigate when link opens in new tab', async ({ page }) => {
await page.goto('/outbound-link.html')
const outboundURL = await page.locator('#link').getAttribute('href')
- const plausibleRequestMock = mockRequest(page, '/api/event')
const navigationRequestMock = mockRequest(page, outboundURL)
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#link', { modifiers: [metaKey()] }),
+ expectedRequests: [{n: 'Outbound Link: Click', p: { url: outboundURL }}]
+ })
- await page.click('#link', { modifiers: [metaKey()] })
-
- expectCustomEvent(await plausibleRequestMock, 'Outbound Link: Click', { url: outboundURL })
expect(await navigationRequestMock, "should not have made navigation request").toBeNull()
})
@@ -20,13 +20,14 @@ test.describe('outbound-links extension', () => {
await page.goto('/outbound-link.html')
const outboundURL = await page.locator('#link').getAttribute('href')
- const plausibleRequestMock = mockRequest(page, '/api/event')
const navigationRequestMock = mockRequest(page, outboundURL)
- await page.click('#link-child')
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#link-child'),
+ expectedRequests: [{n: 'Outbound Link: Click', p: { url: outboundURL }}]
+ })
const navigationRequest = await navigationRequestMock
- expectCustomEvent(await plausibleRequestMock, 'Outbound Link: Click', { url: outboundURL })
expect(navigationRequest.url()).toContain(outboundURL)
})
@@ -34,12 +35,13 @@ test.describe('outbound-links extension', () => {
await page.goto('/outbound-link.html')
const outboundURL = await page.locator('#link-default-prevented').getAttribute('href')
- const plausibleRequestMock = mockRequest(page, '/api/event')
const navigationRequestMock = mockRequest(page, outboundURL)
- await page.click('#link-default-prevented')
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#link-default-prevented'),
+ expectedRequests: [{n: 'Outbound Link: Click', p: { url: outboundURL }}]
+ })
- expectCustomEvent(await plausibleRequestMock, 'Outbound Link: Click', { url: outboundURL })
expect(await navigationRequestMock, "should not have made navigation request").toBeNull()
})
})
diff --git a/tracker/test/pageleave.spec.js b/tracker/test/pageleave.spec.js
index 79ad27822f..e4b17809f6 100644
--- a/tracker/test/pageleave.spec.js
+++ b/tracker/test/pageleave.spec.js
@@ -1,5 +1,5 @@
/* eslint-disable playwright/no-skipped-test */
-const { clickPageElementAndExpectEventRequests, mockRequest } = require('./support/test-utils')
+const { expectPlausibleInAction, pageleaveCooldown } = require('./support/test-utils')
const { test } = require('@playwright/test')
const { LOCAL_SERVER_ADDR } = require('./support/server')
@@ -7,88 +7,166 @@ test.describe('pageleave extension', () => {
test.skip(({browserName}) => browserName === 'webkit', 'Not testable on Webkit')
test('sends a pageleave when navigating to the next page', async ({ page }) => {
- const pageviewRequestMock = mockRequest(page, '/api/event')
- await page.goto('/pageleave.html')
- await pageviewRequestMock
-
- await clickPageElementAndExpectEventRequests(page, '#navigate-away', [
- {n: 'pageleave', u: `${LOCAL_SERVER_ADDR}/pageleave.html`}
- ])
+ await expectPlausibleInAction(page, {
+ action: () => page.goto('/pageleave.html'),
+ expectedRequests: [{n: 'pageview'}]
+ })
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#navigate-away'),
+ expectedRequests: [{n: 'pageleave', u: `${LOCAL_SERVER_ADDR}/pageleave.html`}]
+ })
})
test('sends pageleave and pageview on hash-based SPA navigation', async ({ page }) => {
- const pageviewRequestMock = mockRequest(page, '/api/event')
- await page.goto('/pageleave-hash.html')
- await pageviewRequestMock
-
- await clickPageElementAndExpectEventRequests(page, '#hash-nav', [
- {n: 'pageleave', u: `${LOCAL_SERVER_ADDR}/pageleave-hash.html`},
- {n: 'pageview', u: `${LOCAL_SERVER_ADDR}/pageleave-hash.html#some-hash`}
- ])
+ await expectPlausibleInAction(page, {
+ action: () => page.goto('/pageleave-hash.html'),
+ expectedRequests: [{n: 'pageview'}]
+ })
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#hash-nav'),
+ expectedRequests: [
+ {n: 'pageleave', u: `${LOCAL_SERVER_ADDR}/pageleave-hash.html`},
+ {n: 'pageview', u: `${LOCAL_SERVER_ADDR}/pageleave-hash.html#some-hash`}
+ ]
+ })
})
test('sends pageleave and pageview on history-based SPA navigation', async ({ page }) => {
- const pageviewRequestMock = mockRequest(page, '/api/event')
- await page.goto('/pageleave.html')
- await pageviewRequestMock
-
- await clickPageElementAndExpectEventRequests(page, '#history-nav', [
- {n: 'pageleave', u: `${LOCAL_SERVER_ADDR}/pageleave.html`},
- {n: 'pageview', u: `${LOCAL_SERVER_ADDR}/another-page`}
- ])
+ await expectPlausibleInAction(page, {
+ action: () => page.goto('/pageleave.html'),
+ expectedRequests: [{n: 'pageview'}]
+ })
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#history-nav'),
+ expectedRequests: [
+ {n: 'pageleave', u: `${LOCAL_SERVER_ADDR}/pageleave.html`},
+ {n: 'pageview', u: `${LOCAL_SERVER_ADDR}/another-page`}
+ ]
+ })
})
test('sends pageleave with the manually overridden URL', async ({ page }) => {
await page.goto('/pageleave-manual.html')
- await clickPageElementAndExpectEventRequests(page, '#pageview-trigger-custom-url', [
- {n: 'pageview', u: 'https://example.com/custom/location'}
- ])
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#pageview-trigger-custom-url'),
+ expectedRequests: [{n: 'pageview', u: 'https://example.com/custom/location'}]
+ })
- await clickPageElementAndExpectEventRequests(page, '#navigate-away', [
- {n: 'pageleave', u: 'https://example.com/custom/location'}
- ])
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#navigate-away'),
+ expectedRequests: [{n: 'pageleave', u: 'https://example.com/custom/location'}]
+ })
})
test('does not send pageleave when pageview was not sent in manual mode', async ({ page }) => {
await page.goto('/pageleave-manual.html')
- await clickPageElementAndExpectEventRequests(page, '#navigate-away', [], [
- {n: 'pageleave'}
- ])
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#navigate-away'),
+ refutedRequests: [{n: 'pageleave'}],
+ })
})
test('script.exclusions.hash.pageleave.js sends pageleave only from URLs where a pageview was sent', async ({ page }) => {
const pageBaseURL = `${LOCAL_SERVER_ADDR}/pageleave-hash-exclusions.html`
-
- const pageviewRequestMock = mockRequest(page, '/api/event')
- await page.goto('/pageleave-hash-exclusions.html')
- await pageviewRequestMock
+
+ await expectPlausibleInAction(page, {
+ action: () => page.goto('/pageleave-hash-exclusions.html'),
+ expectedRequests: [{n: 'pageview'}]
+ })
// After the initial pageview is sent, navigate to ignored page ->
// pageleave event is sent from the initial page URL
- await clickPageElementAndExpectEventRequests(page, '#ignored-hash-link', [
- {n: 'pageleave', u: pageBaseURL, h: 1}
- ])
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#ignored-hash-link'),
+ expectedRequests: [{n: 'pageleave', u: pageBaseURL, h: 1}]
+ })
+
+ await pageleaveCooldown(page)
// Navigate from ignored page to a tracked page ->
// no pageleave from the current page, pageview on the next page
- await clickPageElementAndExpectEventRequests(
- page,
- '#hash-link-1',
- [{n: 'pageview', u: `${pageBaseURL}#hash1`, h: 1}],
- [{n: 'pageleave'}]
- )
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#hash-link-1'),
+ expectedRequests: [{n: 'pageview', u: `${pageBaseURL}#hash1`, h: 1}],
+ refutedRequests: [{n: 'pageleave'}]
+ })
+
+ await pageleaveCooldown(page)
// Navigate from a tracked page to another tracked page ->
// pageleave with the last page URL, pageview with the new URL
- await clickPageElementAndExpectEventRequests(
- page,
- '#hash-link-2',
- [
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#hash-link-2'),
+ expectedRequests: [
{n: 'pageleave', u: `${pageBaseURL}#hash1`, h: 1},
{n: 'pageview', u: `${pageBaseURL}#hash2`, h: 1}
],
- )
+ })
+ })
+
+ test('sends pageleave with the same props as pageview (manual extension)', async ({ page }) => {
+ await page.goto('/pageleave-manual.html')
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#pageview-trigger-custom-props'),
+ expectedRequests: [{n: 'pageview', p: {author: 'John'}}]
+ })
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#navigate-away'),
+ expectedRequests: [{n: 'pageleave', p: {author: 'John'}}]
+ })
+ })
+
+ test('sends pageleave with the same props as pageview (pageview-props extension)', async ({ page }) => {
+ await expectPlausibleInAction(page, {
+ action: () => page.goto('/pageleave-pageview-props.html'),
+ expectedRequests: [{n: 'pageview', p: {author: 'John'}}]
+ })
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#navigate-away'),
+ expectedRequests: [{n: 'pageleave', p: {author: 'John'}}]
+ })
+ })
+
+ test('sends pageleave with the same props as pageview (hash navigation / pageview-props extension)', async ({ page }) => {
+ await expectPlausibleInAction(page, {
+ action: () => page.goto('/pageleave-hash-pageview-props.html'),
+ expectedRequests: [{n: 'pageview', p: {}}]
+ })
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#john-post'),
+ expectedRequests: [
+ {n: 'pageleave', p: {}},
+ {n: 'pageview', p: {author: 'john'}}
+ ]
+ })
+
+ await pageleaveCooldown(page)
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#jane-post'),
+ expectedRequests: [
+ {n: 'pageleave', p: {author: 'john'}},
+ {n: 'pageview', p: {author: 'jane'}}
+ ]
+ })
+
+ await pageleaveCooldown(page)
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#home'),
+ expectedRequests: [
+ {n: 'pageleave', p: {author: 'jane'}},
+ {n: 'pageview', p: {}}
+ ]
+ })
})
})
\ No newline at end of file
diff --git a/tracker/test/revenue.spec.js b/tracker/test/revenue.spec.js
index 13893d2126..b2963fb98c 100644
--- a/tracker/test/revenue.spec.js
+++ b/tracker/test/revenue.spec.js
@@ -1,22 +1,22 @@
-const { mockRequest, expectCustomEvent } = require('./support/test-utils')
-const { expect, test } = require('@playwright/test')
+const { expectPlausibleInAction } = require('./support/test-utils')
+const { test } = require('@playwright/test')
test.describe('with revenue script extension', () => {
test('sends revenue currency and amount in manual mode', async ({ page }) => {
- const plausibleRequestMock = mockRequest(page, '/api/event')
await page.goto('/revenue.html')
- await page.click('#manual-purchase')
- const plausibleRequest = await plausibleRequestMock
- expect(plausibleRequest.postDataJSON()["$"]).toEqual({amount: 15.99, currency: "USD"})
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#manual-purchase'),
+ expectedRequests: [{n: "Purchase", $: {amount: 15.99, currency: "USD"}}]
+ })
})
test('sends revenue currency and amount with tagged class name', async ({ page }) => {
- const plausibleRequestMock = mockRequest(page, '/api/event')
await page.goto('/revenue.html')
- await page.click('#tagged-purchase')
- const plausibleRequest = await plausibleRequestMock
- expect(plausibleRequest.postDataJSON()["$"]).toEqual({amount: "13.32", currency: "EUR"})
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#tagged-purchase'),
+ expectedRequests: [{n: "Purchase", $: {amount: "13.32", currency: "EUR"}}]
+ })
})
})
diff --git a/tracker/test/scroll-depth.spec.js b/tracker/test/scroll-depth.spec.js
index a4dcd552d7..edea3c3237 100644
--- a/tracker/test/scroll-depth.spec.js
+++ b/tracker/test/scroll-depth.spec.js
@@ -1,5 +1,5 @@
/* eslint-disable playwright/no-skipped-test */
-const { clickPageElementAndExpectEventRequests, mockRequest } = require('./support/test-utils')
+const { pageleaveCooldown, expectPlausibleInAction } = require('./support/test-utils')
const { test } = require('@playwright/test')
const { LOCAL_SERVER_ADDR } = require('./support/server')
@@ -7,67 +7,80 @@ test.describe('scroll depth', () => {
test.skip(({browserName}) => browserName === 'webkit', 'Not testable on Webkit')
test('sends scroll_depth in the pageleave payload when navigating to the next page', async ({ page }) => {
- const pageviewRequestMock = mockRequest(page, '/api/event')
- await page.goto('/scroll-depth.html')
- await pageviewRequestMock
+ await expectPlausibleInAction(page, {
+ action: () => page.goto('/scroll-depth.html'),
+ expectedRequests: [{n: 'pageview'}]
+ })
await page.evaluate(() => window.scrollBy(0, 300))
await page.evaluate(() => window.scrollBy(0, 0))
- await clickPageElementAndExpectEventRequests(page, '#navigate-away', [
- {n: 'pageleave', u: `${LOCAL_SERVER_ADDR}/scroll-depth.html`, sd: 20}
- ])
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#navigate-away'),
+ expectedRequests: [{n: 'pageleave', u: `${LOCAL_SERVER_ADDR}/scroll-depth.html`, sd: 20}]
+ })
})
test('sends scroll depth on hash navigation', async ({ page }) => {
- const pageviewRequestMock = mockRequest(page, '/api/event')
- await page.goto('/scroll-depth-hash.html')
- await pageviewRequestMock
-
- await clickPageElementAndExpectEventRequests(page, '#about-link', [
- {n: 'pageleave', u: `${LOCAL_SERVER_ADDR}/scroll-depth-hash.html`, sd: 100},
- {n: 'pageview', u: `${LOCAL_SERVER_ADDR}/scroll-depth-hash.html#about`}
- ])
-
- // Wait 600ms before navigating again because pageleave events are throttled to 500ms.
- await page.waitForTimeout(600)
-
- await clickPageElementAndExpectEventRequests(page, '#home-link', [
- {n: 'pageleave', u: `${LOCAL_SERVER_ADDR}/scroll-depth-hash.html#about`, sd: 34},
- {n: 'pageview', u: `${LOCAL_SERVER_ADDR}/scroll-depth-hash.html#home`}
- ])
+ await expectPlausibleInAction(page, {
+ action: () => page.goto('/scroll-depth-hash.html'),
+ expectedRequests: [{n: 'pageview'}]
+ })
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#about-link'),
+ expectedRequests: [
+ {n: 'pageleave', u: `${LOCAL_SERVER_ADDR}/scroll-depth-hash.html`, sd: 100},
+ {n: 'pageview', u: `${LOCAL_SERVER_ADDR}/scroll-depth-hash.html#about`}
+ ]
+ })
+
+ await pageleaveCooldown(page)
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#home-link'),
+ expectedRequests: [
+ {n: 'pageleave', u: `${LOCAL_SERVER_ADDR}/scroll-depth-hash.html#about`, sd: 34},
+ {n: 'pageview', u: `${LOCAL_SERVER_ADDR}/scroll-depth-hash.html#home`}
+ ]
+ })
})
test('document height gets reevaluated after window load', async ({ page }) => {
- const pageviewRequestMock = mockRequest(page, '/api/event')
- await page.goto('/scroll-depth-slow-window-load.html')
- await pageviewRequestMock
+ await expectPlausibleInAction(page, {
+ action: () => page.goto('/scroll-depth-slow-window-load.html'),
+ expectedRequests: [{n: 'pageview'}]
+ })
// Wait for the image to be loaded
await page.waitForFunction(() => {
return document.getElementById('slow-image').complete
})
- await clickPageElementAndExpectEventRequests(page, '#navigate-away', [
- {n: 'pageleave', u: `${LOCAL_SERVER_ADDR}/scroll-depth-slow-window-load.html`, sd: 24}
- ])
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#navigate-away'),
+ expectedRequests: [{n: 'pageleave', u: `${LOCAL_SERVER_ADDR}/scroll-depth-slow-window-load.html`, sd: 24}]
+ })
})
test('dynamically loaded content affects documentHeight', async ({ page }) => {
- const pageviewRequestMock = mockRequest(page, '/api/event')
- await page.goto('/scroll-depth-dynamic-content-load.html')
- await pageviewRequestMock
-
+ await expectPlausibleInAction(page, {
+ action: () => page.goto('/scroll-depth-dynamic-content-load.html'),
+ expectedRequests: [{n: 'pageview'}]
+ })
+
// The link appears dynamically after 500ms.
- await clickPageElementAndExpectEventRequests(page, '#navigate-away', [
- {n: 'pageleave', u: `${LOCAL_SERVER_ADDR}/scroll-depth-dynamic-content-load.html`, sd: 14}
- ])
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#navigate-away'),
+ expectedRequests: [{n: 'pageleave', u: `${LOCAL_SERVER_ADDR}/scroll-depth-dynamic-content-load.html`, sd: 14}]
+ })
})
test('document height gets reevaluated on scroll', async ({ page }) => {
- const pageviewRequestMock = mockRequest(page, '/api/event')
- await page.goto('/scroll-depth-content-onscroll.html')
- await pageviewRequestMock
+ await expectPlausibleInAction(page, {
+ action: () => page.goto('/scroll-depth-content-onscroll.html'),
+ expectedRequests: [{n: 'pageview'}]
+ })
// During the first 3 seconds, the script periodically updates document height
// to account for dynamically loaded content. Since we want to test document
@@ -82,8 +95,9 @@ test.describe('scroll depth', () => {
await page.evaluate(() => window.scrollBy(0, 1000))
- await clickPageElementAndExpectEventRequests(page, '#navigate-away', [
- {n: 'pageleave', u: `${LOCAL_SERVER_ADDR}/scroll-depth-content-onscroll.html`, sd: 80}
- ])
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#navigate-away'),
+ expectedRequests: [{n: 'pageleave', u: `${LOCAL_SERVER_ADDR}/scroll-depth-content-onscroll.html`, sd: 80}]
+ })
})
})
\ No newline at end of file
diff --git a/tracker/test/support/test-utils.js b/tracker/test/support/test-utils.js
index 5225ed58ad..197a99522a 100644
--- a/tracker/test/support/test-utils.js
+++ b/tracker/test/support/test-utils.js
@@ -1,4 +1,10 @@
-const { expect } = require("@playwright/test");
+const { expect, Page } = require("@playwright/test");
+
+// Since pageleave events in the Plausible script are throttled to 500ms, we
+// often need to wait for an artificial timeout before navigating in tests.
+exports.pageleaveCooldown = async function(page) {
+ return page.waitForTimeout(600)
+}
// Mocks an HTTP request call with the given path. Returns a Promise that resolves to the request
// data. If the request is not made, resolves to null after 3 seconds.
@@ -44,38 +50,47 @@ const mockManyRequests = function(page, path, numberOfRequests) {
exports.mockManyRequests = mockManyRequests
-exports.expectCustomEvent = function (request, eventName, eventProps) {
- const payload = request.postDataJSON()
-
- expect(payload.n).toEqual(eventName)
-
- for (const [key, value] of Object.entries(eventProps)) {
- expect(payload.p[key]).toEqual(value)
- }
-}
-
-
/**
* A powerful utility function that makes it easy to assert on the event
- * requests that should or should not have been made after clicking a page
- * element.
- *
- * This function accepts subsets of request bodies (the JSON payloads) as
- * arguments, and compares them with the bodies of the requests that were
- * actually made. For a body subset to match a request, all the key-value
- * pairs present in the subset should also appear in the request body.
+ * requests that should or should not have been made after doing a page
+ * action (e.g. navigating to the page, clicking a page element, etc).
+ *
+ * @param {Page} page - The Playwright Page object.
+ * @param {Object} args - The object configuring the action and related expectations.
+ * @param {Function} args.action - A function that returns a promise. The function is called
+ * without arguments, and is `await`ed. This is the action that should or should not trigger
+ * Plausible requests on the page.
+ * @param {Array} [args.expectedRequests] - A list of partial JSON payloads that get matched
+ * against the bodies of event requests made. An `expectedRequest` is considered as having
+ * occurred if all of its key-value pairs are found from the JSON body of an event request
+ * that was made. The default value is `[]`
+ * @param {Array} [args.refutedRequests] - Same as `expectedRequests` but the opposite. The
+ * expectation passes if none of the made requests match with these partial payloads. Note
+ * that the condition on which a partial payload matches an event request payload is exactly
+ * the same as it is for `expectedRequests`. The default value is `[]`
+ * @param {number} [args.awaitedRequestCount] - Sometimes we might want to wait for more events
+ * to happen, just to make sure they didn't. By default, the number of requests we wait for
+ * is `expectedRequests.length + refutedRequests.length`.
+ * @param {number} [args.expectedRequestCount] - When provided, expects the total amount of
+ * event requests made to match this number.
*/
-exports.clickPageElementAndExpectEventRequests = async function (page, locatorToClick, expectedBodySubsets, refutedBodySubsets = []) {
- const requestsToExpect = expectedBodySubsets.length
- const requestsToAwait = requestsToExpect + refutedBodySubsets.length
+exports.expectPlausibleInAction = async function (page, {
+ action,
+ expectedRequests = [],
+ refutedRequests = [],
+ awaitedRequestCount,
+ expectedRequestCount
+}) {
+ const requestsToExpect = expectedRequestCount ? expectedRequestCount : expectedRequests.length
+ const requestsToAwait = awaitedRequestCount ? awaitedRequestCount : requestsToExpect + refutedRequests.length
const plausibleRequestMockList = mockManyRequests(page, '/api/event', requestsToAwait)
- await page.click(locatorToClick)
+ await action()
const requestBodies = (await plausibleRequestMockList).map(r => r.postDataJSON())
const expectedButNotFoundBodySubsets = []
- expectedBodySubsets.forEach((bodySubset) => {
+ expectedRequests.forEach((bodySubset) => {
const wasFound = requestBodies.some((requestBody) => {
return includesSubset(requestBody, bodySubset)
})
@@ -85,7 +100,7 @@ exports.clickPageElementAndExpectEventRequests = async function (page, locatorTo
const refutedButFoundRequestBodies = []
- refutedBodySubsets.forEach((bodySubset) => {
+ refutedRequests.forEach((bodySubset) => {
const found = requestBodies.find((requestBody) => {
return includesSubset(requestBody, bodySubset)
})
@@ -104,6 +119,21 @@ exports.clickPageElementAndExpectEventRequests = async function (page, locatorTo
function includesSubset(body, subset) {
return Object.keys(subset).every((key) => {
- return body[key] === subset[key]
+ if (typeof subset[key] === 'object') {
+ return typeof body[key] === 'object' && areFlatObjectsEqual(body[key], subset[key])
+ } else {
+ return body[key] === subset[key]
+ }
})
}
+
+// For comparing custom props - all key-value pairs
+// must match but the order is not important.
+function areFlatObjectsEqual(obj1, obj2) {
+ const keys1 = Object.keys(obj1)
+ const keys2 = Object.keys(obj2)
+
+ if (keys1.length !== keys2.length) return false;
+
+ return keys1.every(key => obj2[key] === obj1[key])
+}
diff --git a/tracker/test/tagged-events.spec.js b/tracker/test/tagged-events.spec.js
index ef4e52b8fa..0b94822413 100644
--- a/tracker/test/tagged-events.spec.js
+++ b/tracker/test/tagged-events.spec.js
@@ -1,4 +1,4 @@
-const { mockRequest, mockManyRequests, expectCustomEvent, metaKey } = require('./support/test-utils')
+const { mockRequest, metaKey, expectPlausibleInAction } = require('./support/test-utils')
const { expect, test } = require('@playwright/test')
test.describe('tagged-events extension', () => {
@@ -7,47 +7,57 @@ test.describe('tagged-events extension', () => {
const linkURL = await page.locator('#link').getAttribute('href')
- const plausibleRequestMock = mockRequest(page, '/api/event')
- await page.click('#link')
- expectCustomEvent(await plausibleRequestMock, 'Payment Complete', { amount: '100', method: "Credit Card", url: linkURL })
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#link'),
+ expectedRequests: [{n: 'Payment Complete', p: {amount: '100', method: "Credit Card", url: linkURL}}]
+ })
})
test('tracks a tagged form submit with custom props when submitting by pressing enter', async ({ page }) => {
await page.goto('/tagged-event.html')
- const plausibleRequestMock = mockRequest(page, '/api/event')
- const inputLocator = page.locator('#form-text-input')
- await inputLocator.type('some input')
- await inputLocator.press('Enter')
+ const submitForm = async function() {
+ const inputLocator = page.locator('#form-text-input')
+ await inputLocator.fill('some input')
+ await inputLocator.press('Enter')
+ }
- expectCustomEvent(await plausibleRequestMock, 'Signup', { type: "Newsletter" })
+ await expectPlausibleInAction(page, {
+ action: submitForm,
+ expectedRequests: [{n: 'Signup', p: {type: "Newsletter"}}]
+ })
})
test('tracks submit on a form with a tagged parent when submit button is clicked', async ({ page }) => {
await page.goto('/tagged-event.html')
- const plausibleRequestMockList = mockManyRequests(page, '/api/event', 2)
-
- await page.click('#submit-form-with-tagged-parent')
-
- const requests = await plausibleRequestMockList
-
- expect(requests.length).toBe(1)
- expectCustomEvent(requests[0], "Form Submit", {})
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#submit-form-with-tagged-parent'),
+ expectedRequests: [{n: 'Form Submit', p: {}}],
+ awaitedRequestCount: 2,
+ expectedRequestCount: 1
+ })
})
test('tracks click and auxclick on any tagged HTML element', async ({ page }) => {
await page.goto('/tagged-event.html')
- const plausibleRequestMockList = mockManyRequests(page, '/api/event', 3)
+ const expectedRequests = [{n: 'Custom Event', p: { foo: "bar" }}]
- await page.click('#button')
- await page.click('#span')
- await page.click('#div', { modifiers: [metaKey()] })
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#button'),
+ expectedRequests
+ })
- const requests = await plausibleRequestMockList
- expect(requests.length).toBe(3)
- requests.forEach(request => expectCustomEvent(request, 'Custom Event', { foo: "bar" }))
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#span'),
+ expectedRequests
+ })
+
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#div', { modifiers: [metaKey()] }),
+ expectedRequests
+ })
})
test('does not track elements without plausible-event-name class + link elements navigate', async ({ page }) => {
@@ -70,28 +80,31 @@ test.describe('tagged-events extension', () => {
test('tracks tagged HTML elements when their child element is clicked', async ({ page }) => {
await page.goto('/tagged-event.html')
- const plausibleRequestMockList = mockManyRequests(page, '/api/event', 2)
+ const expectedRequests = [
+ {n: 'Custom Event', p: { foo: "bar", url: "https://awesome.website.com/payment/"}}
+ ]
- await page.click('#h2-with-link-parent', { modifiers: [metaKey()] })
- await page.click('#link-with-div-parent')
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#h2-with-link-parent', { modifiers: [metaKey()] }),
+ expectedRequests
+ })
- const requests = await plausibleRequestMockList
- expect(requests.length).toBe(2)
- requests.forEach(request => expectCustomEvent(request, 'Custom Event', { foo: "bar" }))
+ await expectPlausibleInAction(page, {
+ action: () => page.click('#link-with-div-parent'),
+ expectedRequests
+ })
})
test('tracks tagged element that is dynamically added to the DOM', async ({ page }) => {
await page.goto('/tagged-event.html')
- const plausibleRequestMock = mockRequest(page, '/api/event')
-
const buttonLocator = page.locator('#dynamic-tagged-button')
await buttonLocator.waitFor({state: 'visible'})
- await page.waitForTimeout(500)
-
- await buttonLocator.click()
- expectCustomEvent(await plausibleRequestMock, 'Custom Event', {})
+ await expectPlausibleInAction(page, {
+ action: () => buttonLocator.click(),
+ expectedRequests: [{n: 'Custom Event', p: {}}]
+ })
})
test('does not track clicks inside a tagged form, except submit click', async ({ page }) => {