From 56164a15b48e60861038c8e62d3eec75bb94db23 Mon Sep 17 00:00:00 2001
From: Adriaan <1079135+adriaandotcom@users.noreply.github.com>
Date: Tue, 27 May 2025 17:23:56 +0200
Subject: [PATCH 1/2] test: add jsdom unit tests
---
README.md | 2 ++
package-lock.json | 1 +
package.json | 2 ++
test/unit/default.test.js | 52 +++++++++++++++++++++++++++++++++++++++
4 files changed, 57 insertions(+)
create mode 100644 test/unit/default.test.js
diff --git a/README.md b/README.md
index e2d265fe..29f589cd 100644
--- a/README.md
+++ b/README.md
@@ -26,6 +26,8 @@ If you contribute, make sure to use `npm run build`, copy the script to a websit
Just run `npm run watch` and every file will be validated and compiled on save. We minify our scripts with [UglifyJS](http://lisperator.net/uglifyjs/), a well-known JavaScript minifier.
+You can quickly run the unit tests with `npm run test:unit`. This command doesn't rely on BrowserStack and is handy for local checks.
+
The most important file of the repository is [`/src/default.js`](src/default.js)
## Device testing is sponsored by BrowserStack
diff --git a/package-lock.json b/package-lock.json
index 7748693a..21465501 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -18,6 +18,7 @@
"mocha": "^6.2.3",
"nodemon": "^1.19.4",
"request": "^2.88.0",
+ "jsdom": "^22.1.0",
"selenium-webdriver": "^4.3.1",
"uglify-js": "^3.9.4",
"uuid-validate": "0.0.3"
diff --git a/package.json b/package.json
index e8fe1bba..3f8ac7b8 100644
--- a/package.json
+++ b/package.json
@@ -9,6 +9,7 @@
"build": "node compile.js",
"pretest": "npm run build -- testing",
"test": "node -r dotenv/config ./test/index.js",
+ "test:unit": "mocha ./test/unit",
"posttest": "npm run build"
},
"repository": {
@@ -32,6 +33,7 @@
"mocha": "^6.2.3",
"nodemon": "^1.19.4",
"request": "^2.88.0",
+ "jsdom": "^22.1.0",
"selenium-webdriver": "^4.3.1",
"uglify-js": "^3.9.4",
"uuid-validate": "0.0.3"
diff --git a/test/unit/default.test.js b/test/unit/default.test.js
new file mode 100644
index 00000000..af29105e
--- /dev/null
+++ b/test/unit/default.test.js
@@ -0,0 +1,52 @@
+const { JSDOM } = require('jsdom');
+const fs = require('fs');
+const path = require('path');
+const vm = require('vm');
+const { expect } = require('chai');
+
+describe('default script', function () {
+ it('sends pageview and event', function () {
+ const dom = new JSDOM('
', {
+ url: 'https://example.com/'
+ });
+
+ const requests = [];
+
+ dom.window.Image = function () {
+ return {
+ set src(value) {
+ requests.push({ type: 'image', url: value });
+ }
+ };
+ };
+
+ dom.window.navigator.sendBeacon = function (url, data) {
+ requests.push({ type: 'beacon', url, data });
+ return true;
+ };
+
+ const context = vm.createContext({
+ window: dom.window,
+ document: dom.window.document,
+ navigator: dom.window.navigator,
+ console: dom.window.console,
+ Image: dom.window.Image,
+ });
+
+ const scriptPath = path.resolve(__dirname, '../../dist/latest/latest.dev.js');
+ const scriptContent = fs.readFileSync(scriptPath, 'utf8');
+ vm.runInContext(scriptContent, context);
+
+ expect(requests.length).to.be.greaterThan(0);
+ const pvUrl = new URL(requests[0].url);
+ expect(pvUrl.pathname).to.equal('/simple.gif');
+ expect(pvUrl.searchParams.get('type')).to.equal('pageview');
+
+ dom.window.sa_event('unit_test');
+
+ expect(requests.length).to.be.greaterThan(1);
+ const evUrl = new URL(requests[requests.length - 1].url);
+ expect(evUrl.searchParams.get('type')).to.equal('event');
+ expect(evUrl.searchParams.get('event')).to.equal('unit_test');
+ });
+});
From 73d14c491bea72af9da0a68ed9507b757cd72522 Mon Sep 17 00:00:00 2001
From: adriaandotcom
Date: Tue, 27 May 2025 15:24:16 +0000
Subject: [PATCH 2/2] Run prettier via GitHub Action
---
compile.js | 20 ++++++-------
playground/callback.html | 15 +++++-----
playground/events.html | 17 +++++------
src/auto-events.js | 2 +-
src/default.js | 56 ++++++++++++++++++------------------
test/helpers/get-browsers.js | 32 ++++++++++-----------
test/helpers/index.js | 4 +--
test/helpers/server.js | 2 +-
test/index.js | 14 ++++-----
test/test-beacon.js | 18 ++++++------
test/test-events.js | 24 ++++++++--------
test/test-no-pushstate.js | 12 ++++----
test/test-one-beacon.js | 16 +++++------
test/test-pushstate.js | 16 +++++------
test/unit/default.test.js | 43 ++++++++++++++-------------
15 files changed, 148 insertions(+), 143 deletions(-)
diff --git a/compile.js b/compile.js
index 52f4bbf1..343e22de 100644
--- a/compile.js
+++ b/compile.js
@@ -30,21 +30,21 @@ const fillTemplate = (template, { overwriteOptions = null } = {}) => {
return template
.replace(
/\{\{\s?nginxHost\s?\}\}/gi,
- ''
+ '',
)
.replace(
/\{\{\s?nginxProxyHost\s?\}\}/gi,
- ''
+ '',
)
.replace(
/\\?"\{\{\s?overwriteOptions\s?\}\}\\?"/gi,
overwriteOptions
? JSON.stringify(overwriteOptions).replace(/:"([^"]+)"/gi, ":$1")
- : "{}"
+ : "{}",
)
.replace(
/"\{\{\s?cloudFlareCustomDomain\s?\}\}"/gi,
- 'INSTALL_OPTIONS.custom_domain || "queue.simpleanalyticscdn.com"'
+ 'INSTALL_OPTIONS.custom_domain || "queue.simpleanalyticscdn.com"',
);
};
@@ -284,7 +284,7 @@ const files = templates.reduce((list, template) => {
if (template.variables.sri) {
list.push(
{ ...template, variables: { ...template.variables, sri: true } },
- { ...template, variables: { ...template.variables, sri: false } }
+ { ...template, variables: { ...template.variables, sri: false } },
);
} else {
list.push(template);
@@ -346,7 +346,7 @@ for (const file of files) {
filename: originalFileName,
url: `${finalFileName}.map`,
},
- }
+ },
)
: {
code: prepend + rawCode,
@@ -374,7 +374,7 @@ for (const file of files) {
RED,
`[${name}][ERROR] ${input
.split("/")
- .pop()} ${description} at line ${lineNumber} position ${index}`
+ .pop()} ${description} at line ${lineNumber} position ${index}`,
);
continue;
}
@@ -402,7 +402,7 @@ for (const file of files) {
let write = code.replace(
/sourceMappingURL=latest\.js\.map/gi,
- `sourceMappingURL=${cdnFileName}.map`
+ `sourceMappingURL=${cdnFileName}.map`,
);
fs.writeFileSync(versionFile, write);
@@ -410,7 +410,7 @@ for (const file of files) {
if (compiledMap) {
let writeCompiled = compiledMap.replace(
/latest\.source\.js/gi,
- cdnFileName
+ cdnFileName,
);
fs.writeFileSync(`${versionFile}.map`, writeCompiled);
@@ -438,7 +438,7 @@ for (const file of files) {
console.log(
` ${name.toLowerCase()} ${fill1}Compiled ${sourceName} ${fill2} ${bytesZeroFilled} bytes ${
variables.sri ? " (SRI)" : ""
- }`
+ }`,
);
}
diff --git a/playground/callback.html b/playground/callback.html
index fd6069af..523f214b 100644
--- a/playground/callback.html
+++ b/playground/callback.html
@@ -1,4 +1,4 @@
-
+
@@ -46,7 +46,8 @@
@font-face {
font-family: "Space Grotesk";
font-weight: 500;
- src: url("https://assets.simpleanalytics.com/fonts/SpaceGrotesk-Medium.woff2")
+ src:
+ url("https://assets.simpleanalytics.com/fonts/SpaceGrotesk-Medium.woff2")
format("woff2"),
url("https://assets.simpleanalytics.com/fonts/SpaceGrotesk-Medium.woff")
format("woff");
@@ -54,7 +55,8 @@
@font-face {
font-family: "Space Grotesk";
font-weight: 400;
- src: url("https://assets.simpleanalytics.com/fonts/SpaceGrotesk-Regular.woff2")
+ src:
+ url("https://assets.simpleanalytics.com/fonts/SpaceGrotesk-Regular.woff2")
format("woff2"),
url("https://assets.simpleanalytics.com/fonts/SpaceGrotesk-Regular.woff")
format("woff");
@@ -179,9 +181,8 @@ Automated events
return param;
})
.join(" ");
- document.querySelector(
- "textarea"
- ).value += `${type.toUpperCase()}: ${line}\n`;
+ document.querySelector("textarea").value +=
+ `${type.toUpperCase()}: ${line}\n`;
}
console.log = function () {
@@ -253,7 +254,7 @@ Automated events
});
const callbackMetadataLink = document.querySelector(
- "[data-metadata-callback]"
+ "[data-metadata-callback]",
);
callbackMetadataLink.addEventListener("click", (event) => {
event.preventDefault();
diff --git a/playground/events.html b/playground/events.html
index 05f871a2..6e6336a3 100644
--- a/playground/events.html
+++ b/playground/events.html
@@ -1,4 +1,4 @@
-
+
@@ -33,9 +33,9 @@
},
() => {
console.info(
- "Simple Analytics auto events: collected before_script_load"
+ "Simple Analytics auto events: collected before_script_load",
);
- }
+ },
);
@@ -67,7 +67,8 @@
@font-face {
font-family: "Space Grotesk";
font-weight: 500;
- src: url("https://assets.simpleanalytics.com/fonts/SpaceGrotesk-Medium.woff2")
+ src:
+ url("https://assets.simpleanalytics.com/fonts/SpaceGrotesk-Medium.woff2")
format("woff2"),
url("https://assets.simpleanalytics.com/fonts/SpaceGrotesk-Medium.woff")
format("woff");
@@ -75,7 +76,8 @@
@font-face {
font-family: "Space Grotesk";
font-weight: 400;
- src: url("https://assets.simpleanalytics.com/fonts/SpaceGrotesk-Regular.woff2")
+ src:
+ url("https://assets.simpleanalytics.com/fonts/SpaceGrotesk-Regular.woff2")
format("woff2"),
url("https://assets.simpleanalytics.com/fonts/SpaceGrotesk-Regular.woff")
format("woff");
@@ -206,9 +208,8 @@ Automated events
return param;
})
.join(" ");
- document.querySelector(
- "textarea"
- ).value += `${type.toUpperCase()}: ${line}\n`;
+ document.querySelector("textarea").value +=
+ `${type.toUpperCase()}: ${line}\n`;
}
console.log = function () {
diff --git a/src/auto-events.js b/src/auto-events.js
index 0df03611..745d1e8d 100644
--- a/src/auto-events.js
+++ b/src/auto-events.js
@@ -155,7 +155,7 @@
/^https?:\/\//i.test(link.href) &&
new RegExp(
"\\.(" + (optionsLink.downloadsExtensions || []).join("|") + ")$",
- "i"
+ "i",
).test(link.pathname)
) {
collect = "download";
diff --git a/src/default.js b/src/default.js
index dfeccbd9..da412b2a 100644
--- a/src/default.js
+++ b/src/default.js
@@ -8,7 +8,7 @@
version,
defaultNamespace,
sendError,
- warn
+ warn,
) {
try {
/////////////////////
@@ -117,8 +117,8 @@
return Array.isArray(csv)
? csv
: isString(csv) && csv.length
- ? csv.split(/, ?/)
- : [];
+ ? csv.split(/, ?/)
+ : [];
};
var isObject = function (object) {
@@ -152,7 +152,7 @@
/** if ignoremetrics **/
// Customers can skip data points
var ignoreMetrics = convertCommaSeparatedToArray(
- overwriteOptions.ignoreMetrics || attr(scriptElement, "ignore-metrics")
+ overwriteOptions.ignoreMetrics || attr(scriptElement, "ignore-metrics"),
);
/** endif **/
@@ -213,7 +213,7 @@
try {
return assign(
metadata,
- metadataCollectorFunction.call(window, assign(metadata, data))
+ metadataCollectorFunction.call(window, assign(metadata, data)),
);
} catch (error) {
warnInFunction("metadata", error);
@@ -284,7 +284,7 @@
ignorePage === path ||
new RegExp(
"^" + filterRegex(ignorePage).replace(/\\\*/gi, "(.*)") + "$",
- "i"
+ "i",
).test(path)
)
return trueVar;
@@ -374,7 +374,7 @@
path: loc.pathname,
}),
undefinedVar,
- trueVar
+ trueVar,
);
};
@@ -387,7 +387,7 @@
sendError(event.message);
}
},
- falseVar
+ falseVar,
);
/** endif **/
@@ -438,14 +438,14 @@
/** if ignorepages **/
// Customers can ignore certain pages
var ignorePages = convertCommaSeparatedToArray(
- overwriteOptions.ignorePages || attr(scriptElement, "ignore-pages")
+ overwriteOptions.ignorePages || attr(scriptElement, "ignore-pages"),
);
/** endif **/
/** if allowparams **/
// Customers can allow params
var allowParams = convertCommaSeparatedToArray(
- overwriteOptions.allowParams || attr(scriptElement, "allow-params")
+ overwriteOptions.allowParams || attr(scriptElement, "allow-params"),
);
/** endif **/
@@ -453,7 +453,7 @@
// Customers can allow params
var nonUniqueHostnames = convertCommaSeparatedToArray(
overwriteOptions.nonUniqueHostnames ||
- attr(scriptElement, "non-unique-hostnames")
+ attr(scriptElement, "non-unique-hostnames"),
);
/** endif **/
@@ -553,12 +553,12 @@
/** if ignorednt **/
if (!collectDnt && doNotTrack in nav && nav[doNotTrack] == "1")
return warn(
- notSendingWhen + doNotTrack + " is enabled. See " + docsUrl + "/dnt"
+ notSendingWhen + doNotTrack + " is enabled. See " + docsUrl + "/dnt",
);
/** else **/
if (doNotTrack in nav && nav[doNotTrack] == "1")
return warn(
- notSendingWhen + doNotTrack + " is enabled. See " + docsUrl + "/dnt"
+ notSendingWhen + doNotTrack + " is enabled. See " + docsUrl + "/dnt",
);
/** endif **/
@@ -573,7 +573,7 @@
locationHostname +
". See " +
docsUrl +
- "/overwrite-domain-name"
+ "/overwrite-domain-name",
);
/////////////////////
@@ -644,7 +644,7 @@
hiddenStart = now();
} else msHidden += now() - hiddenStart;
},
- falseVar
+ falseVar,
);
/** endif **/
@@ -660,15 +660,15 @@
body[offsetHeight] || 0,
documentElement[clientHeight] || 0,
documentElement[scrollHeight] || 0,
- documentElement[offsetHeight] || 0
+ documentElement[offsetHeight] || 0,
);
return Math.min(
100,
Math.round(
(100 * ((documentElement.scrollTop || 0) + documentClientHeight)) /
height /
- 5
- ) * 5
+ 5,
+ ) * 5,
);
} catch (error) {
warn(error);
@@ -683,7 +683,7 @@
function () {
if (scrolled < position()) scrolled = position();
},
- falseVar
+ falseVar,
);
});
/** endif **/
@@ -737,7 +737,7 @@
isPushState,
deleteSourceInfo,
sameSite,
- metadata
+ metadata,
) {
if (isPushState) sendOnLeave("" + payload.page_id, trueVar);
if (collectDataOnLeave) payload.page_id = uuid();
@@ -782,7 +782,7 @@
page.viewport_height =
Math.max(
documentElement[clientHeight] || 0,
- window.innerHeight || 0
+ window.innerHeight || 0,
) || null;
}
/** endif **/
@@ -853,7 +853,7 @@
isPushState,
isPushState || userNavigated || !collectMetricByString("r"), // r = referrers
sameSite,
- metadata
+ metadata,
);
};
@@ -920,7 +920,7 @@
function () {
pageview(1);
},
- falseVar
+ falseVar,
);
addEventListenerFunc(
@@ -928,7 +928,7 @@
function () {
pageview(1);
},
- falseVar
+ falseVar,
);
}
/** endif **/
@@ -941,7 +941,7 @@
function () {
pageview(1);
},
- falseVar
+ falseVar,
);
}
/** endif **/
@@ -988,7 +988,7 @@
if (validTypes.indexOf(typeof eventOutput) < 0) {
warnInFunction(
eventFunctionName,
- event + " returns no string: " + eventOutput
+ event + " returns no string: " + eventOutput,
);
return callback();
}
@@ -1022,7 +1022,7 @@
metadata: stringify(metadata),
/** endif **/
}),
- callback
+ callback,
);
}
};
@@ -1065,5 +1065,5 @@
"{{baseUrl}}",
"{{apiUrlPrefix}}",
"{{scriptName}}",
- "{{namespace}}"
+ "{{namespace}}",
);
diff --git a/test/helpers/get-browsers.js b/test/helpers/get-browsers.js
index fba8d423..2cc449f7 100644
--- a/test/helpers/get-browsers.js
+++ b/test/helpers/get-browsers.js
@@ -38,10 +38,10 @@ module.exports = async () => {
browser_main_version: version(item.browser_version),
}))
.sort((left, right) =>
- version(left.browser_version) > version(right.browser_version) ? -1 : 1
+ version(left.browser_version) > version(right.browser_version) ? -1 : 1,
)
.slice(0, 2),
- ["os", "browser_main_version"]
+ ["os", "browser_main_version"],
);
const chrome = makeUnique(
@@ -54,18 +54,18 @@ module.exports = async () => {
);
})
.sort((left, right) =>
- version(left.browser_version) > version(right.browser_version) ? -1 : 1
+ version(left.browser_version) > version(right.browser_version) ? -1 : 1,
),
- ["os", "os_version"]
+ ["os", "os_version"],
);
const ios = makeUnique(
all
.filter(({ browser }) => browser === "iphone")
.sort((left, right) =>
- version(left.browser_version) > version(right.browser_version) ? -1 : 1
+ version(left.browser_version) > version(right.browser_version) ? -1 : 1,
),
- ["os", "os_version"]
+ ["os", "os_version"],
);
const android = makeUnique(
@@ -76,9 +76,9 @@ module.exports = async () => {
os_main_version: parseInt(item.os_version.split(".")[0], 10),
}))
.sort((left, right) =>
- version(left.os_version) > version(right.os_version) ? -1 : 1
+ version(left.os_version) > version(right.os_version) ? -1 : 1,
),
- ["os", "os_main_version"]
+ ["os", "os_main_version"],
);
const safari = makeUnique(
@@ -96,10 +96,10 @@ module.exports = async () => {
browser_main_version: version(item.browser_version),
}))
.sort((left, right) =>
- left.browser_main_version > right.browser_main_version ? -1 : 1
+ left.browser_main_version > right.browser_main_version ? -1 : 1,
)
.slice(0, 4),
- ["os", "browser_main_version"]
+ ["os", "browser_main_version"],
).slice(0, 5);
const firefox = makeUnique(
@@ -112,9 +112,9 @@ module.exports = async () => {
);
})
.sort((left, right) =>
- version(left.browser_version) > version(right.browser_version) ? -1 : 1
+ version(left.browser_version) > version(right.browser_version) ? -1 : 1,
),
- ["os"]
+ ["os"],
);
const opera = makeUnique(
@@ -128,9 +128,9 @@ module.exports = async () => {
);
})
.sort((left, right) =>
- version(left.browser_version) > version(right.browser_version) ? -1 : 1
+ version(left.browser_version) > version(right.browser_version) ? -1 : 1,
),
- ["os"]
+ ["os"],
);
const ipads = makeUnique(
@@ -139,9 +139,9 @@ module.exports = async () => {
return browser === "ipad";
})
.sort((left, right) =>
- version(left.os_version) > version(right.os_version) ? -1 : 1
+ version(left.os_version) > version(right.os_version) ? -1 : 1,
),
- ["os_version"]
+ ["os_version"],
);
const browsers = [
diff --git a/test/helpers/index.js b/test/helpers/index.js
index 25544d7c..66d8b727 100644
--- a/test/helpers/index.js
+++ b/test/helpers/index.js
@@ -27,7 +27,7 @@ module.exports.makeUnique = (array = [], keys = []) => {
return array.reduce((list, item) => {
const has = list.find((listItem) =>
- keys.every((key) => listItem[key] === item[key])
+ keys.every((key) => listItem[key] === item[key]),
);
if (!has) list.push(item);
return list;
@@ -92,7 +92,7 @@ module.exports.navigate = async ({ browser, os, name, driver, commands }) => {
`${amount || 1}x`,
typeof exceeded === "number"
? `(found request in ${exceeded}ms)`
- : `(exceeded timeout)`
+ : `(exceeded timeout)`,
);
} else if (script) {
log(`script (${name})`, `${localhost}/?${searchParams}`);
diff --git a/test/helpers/server.js b/test/helpers/server.js
index 18ef4dfe..cf4353bc 100644
--- a/test/helpers/server.js
+++ b/test/helpers/server.js
@@ -66,7 +66,7 @@ const route = async (req, res) => {
Simple Analytics Test
Path: ${pathname}
- `
+ `,
);
return res.end();
}
diff --git a/test/index.js b/test/index.js
index 8bafc945..fc705c9f 100644
--- a/test/index.js
+++ b/test/index.js
@@ -144,7 +144,7 @@ const log = (...messages) => DEBUG && console.log(" => Test:", ...messages);
if (!BROWSERSTACK_USERNAME || !BROWSERSTACK_ACCESS_KEY) {
console.error(
- "BROWSERSTACK_USERNAME nor BROWSERSTACK_ACCESS_KEY are not defined."
+ "BROWSERSTACK_USERNAME nor BROWSERSTACK_ACCESS_KEY are not defined.",
);
process.exit(1);
}
@@ -213,7 +213,7 @@ const getDeviceName = ({
const suiteInstance = Mocha.Suite.create(
mochaInstance.suite,
- "Public Script Test Suite"
+ "Public Script Test Suite",
);
if (CI)
@@ -223,16 +223,16 @@ const getDeviceName = ({
async function () {
expect(
browsers,
- "Should have more than 20 browsers"
+ "Should have more than 20 browsers",
).to.have.lengthOf.at.least(20);
- }
- )
+ },
+ ),
);
suiteInstance.addTest(
new Mocha.Test(`Test Node.js environment`, async function () {
expect(process.version, "Should use Node.js 16.16").to.match(/^v16\.16/);
- })
+ }),
);
const appendBrowserData = (browser) => {
@@ -409,7 +409,7 @@ const getDeviceName = ({
const testName = `Testing ${browser.name} (${index + 1}/${total})`;
const nextBrowser = browsers[index + 1];
suiteInstance.addTest(
- new Mocha.Test(testName, () => test(browser, nextBrowser))
+ new Mocha.Test(testName, () => test(browser, nextBrowser)),
);
}
diff --git a/test/test-beacon.js b/test/test-beacon.js
index b9aefce1..b47a98de 100644
--- a/test/test-beacon.js
+++ b/test/test-beacon.js
@@ -9,48 +9,48 @@ module.exports = async () => {
expect(
beaconRequests,
- "There are not enough beacon requests found"
+ "There are not enough beacon requests found",
).to.have.lengthOf(2);
expect(
beaconRequests[0].pathname,
- "First beacon request should be send via GIF"
+ "First beacon request should be send via GIF",
).to.equal("/simple.gif");
expect(
beaconRequests[1].pathname,
- "Second beacon request should be send via /append"
+ "Second beacon request should be send via /append",
).to.equal("/append");
beaconRequests.map((request) => {
expect(
request,
- "There are no page view requests with body found"
+ "There are no page view requests with body found",
).to.have.property("body");
expect(
request.body,
- "All required keys should be present"
+ "All required keys should be present",
).to.include.all.keys(["duration", "scrolled", "original_id", "type"]);
expect(
UUIDvalidate(request.body.original_id, 4),
- "original_id should be a valid UUIDv4"
+ "original_id should be a valid UUIDv4",
).to.be.true;
expect(
parseInt(request.body.scrolled, 10),
- "Scrolled should be close to 35 percent"
+ "Scrolled should be close to 35 percent",
).to.be.closeTo(35, 5);
expect(
parseInt(request.body.duration, 10),
- "Duration should be a valid number"
+ "Duration should be a valid number",
).to.be.a("number");
expect(
parseInt(request.body.duration, 10),
- "Duration should be close to 0 or 1 second"
+ "Duration should be close to 0 or 1 second",
).to.be.closeTo(2, 2);
});
};
diff --git a/test/test-events.js b/test/test-events.js
index 04e633d2..734dd018 100644
--- a/test/test-events.js
+++ b/test/test-events.js
@@ -10,31 +10,31 @@ module.exports = async ({ os, browser }) => {
expect(requests, "There should be two event requests").to.have.lengthOf(3);
expect(requests[0].body.event, "Event should be 'event_123'").to.equal(
- "event_123"
+ "event_123",
);
expect(requests[1].body.event, "Event should be 'functionoutput'").to.equal(
- "functionoutput"
+ "functionoutput",
);
expect(requests[2].body.metadata, "Event should have metadata").to.contain(
- '","bool":false,"int":20301,"string":"hi\'/301%20uas@#*0"}'
+ '","bool":false,"int":20301,"string":"hi\'/301%20uas@#*0"}',
);
expect(
new Date(JSON.parse(requests[2].body.metadata).date),
- "Event should have a date in the last 5 minutes"
+ "Event should have a date in the last 5 minutes",
).to.greaterThan(new Date(Date.now() - 300000));
requests.map((request) => {
expect(
request,
- "There are no event requests with body found"
+ "There are no event requests with body found",
).to.have.property("body");
expect(
request.body,
- "All required keys should be present"
+ "All required keys should be present",
).to.include.all.keys([
"version",
"hostname",
@@ -47,34 +47,34 @@ module.exports = async ({ os, browser }) => {
expect(
UUIDvalidate(request.body.id, 4),
- "event id should be a valid UUIDv4"
+ "event id should be a valid UUIDv4",
).to.be.true;
expect(
UUIDvalidate(request.body.session_id, 4),
- "session_id should be a valid UUIDv4"
+ "session_id should be a valid UUIDv4",
).to.be.true;
expect(
UUIDvalidate(request.body.page_id, 4),
- "page_id should be a valid UUIDv4"
+ "page_id should be a valid UUIDv4",
).to.be.true;
if (os === "ios" || browser === "safari") {
expect(
request.body.hostname,
- "Hostname should be bs-local.com on OS X Safari"
+ "Hostname should be bs-local.com on OS X Safari",
).to.equal("bs-local.com:3000");
} else {
expect(
request.body.hostname,
- "Hostname should be localhost on non iOS"
+ "Hostname should be localhost on non iOS",
).to.equal("localhost:3000");
}
expect(
parseInt(request.body.version, 10),
- "Version should be a valid number"
+ "Version should be a valid number",
).to.be.a("number");
});
};
diff --git a/test/test-no-pushstate.js b/test/test-no-pushstate.js
index 0dda1a39..503a7209 100644
--- a/test/test-no-pushstate.js
+++ b/test/test-no-pushstate.js
@@ -11,28 +11,28 @@ module.exports = async () => {
expect(
pageViewRequests,
- "There are not enough page views requests found"
+ "There are not enough page views requests found",
).to.have.lengthOf(2);
expect(
pageViewRequests[0].body.unique,
- "The first visit should be unique"
+ "The first visit should be unique",
).to.equal("true");
expect(
pageViewRequests[1].body.unique,
- "The second visit should not be unique"
+ "The second visit should not be unique",
).to.equal("false");
pageViewRequests.map((request) => {
expect(
request,
- "There are no page view requests with body found"
+ "There are no page view requests with body found",
).to.have.property("body");
expect(
request.body,
- "All required keys should be present"
+ "All required keys should be present",
).to.include.all.keys([
"hostname",
"https",
@@ -53,7 +53,7 @@ module.exports = async () => {
expect(
parseInt(request.body.version, 10),
- "Version should be a valid number"
+ "Version should be a valid number",
).to.be.a("number");
// We replace "https:" with "http:" string on CI
diff --git a/test/test-one-beacon.js b/test/test-one-beacon.js
index 03d6ee9b..ff7cbaf8 100644
--- a/test/test-one-beacon.js
+++ b/test/test-one-beacon.js
@@ -9,24 +9,24 @@ module.exports = async () => {
expect(
beaconRequests,
- "There should be 1 beacon type request"
+ "There should be 1 beacon type request",
).to.have.lengthOf(1);
const request = beaconRequests[0];
expect(
request.pathname,
- "First beacon request should be send via GIF"
+ "First beacon request should be send via GIF",
).to.equal("/simple.gif");
expect(
request,
- "There are no beacon requests with body found"
+ "There are no beacon requests with body found",
).to.have.property("body");
expect(
request.body,
- "All required keys should be present"
+ "All required keys should be present",
).to.include.all.keys([
"hostname",
"duration",
@@ -37,21 +37,21 @@ module.exports = async () => {
expect(
UUIDvalidate(request.body.original_id, 4),
- "original_id should be a valid UUIDv4"
+ "original_id should be a valid UUIDv4",
).to.be.true;
expect(
parseInt(request.body.scrolled, 10),
- "Scrolled should be close to 35 percent"
+ "Scrolled should be close to 35 percent",
).to.be.closeTo(35, 5);
expect(
parseInt(request.body.duration, 10),
- "Duration should be a valid number"
+ "Duration should be a valid number",
).to.be.a("number");
expect(
parseInt(request.body.version, 10),
- "Version should be a valid number"
+ "Version should be a valid number",
).to.be.a("number");
};
diff --git a/test/test-pushstate.js b/test/test-pushstate.js
index bd3781b5..62e9540f 100644
--- a/test/test-pushstate.js
+++ b/test/test-pushstate.js
@@ -11,23 +11,23 @@ module.exports = async () => {
expect(
pageViewRequests,
- "There are not enough page views requests found"
+ "There are not enough page views requests found",
).to.have.lengthOf(2);
expect([true, "true"], "The first visit should be unique").to.include(
- pageViewRequests[0].body.unique
+ pageViewRequests[0].body.unique,
);
expect([false, "false"], "The second visit should not be unique").to.include(
- pageViewRequests[1].body.unique
+ pageViewRequests[1].body.unique,
);
expect(pageViewRequests[0].body.query, "Query should exist").to.equal(
- "project=project_x&utm_source=utm_source&medium=medium&ref=ref"
+ "project=project_x&utm_source=utm_source&medium=medium&ref=ref",
);
expect(pageViewRequests[1].body.query, "Query should not exist").to.equal(
- "project=project_x"
+ "project=project_x",
);
// Seconds page referrer should be the first page (ending with /)
@@ -36,12 +36,12 @@ module.exports = async () => {
pageViewRequests.map((request) => {
expect(
request,
- "There are no page view requests with body found"
+ "There are no page view requests with body found",
).to.have.property("body");
expect(
request.body,
- "All required keys should be present"
+ "All required keys should be present",
).to.include.all.keys([
"hostname",
"https",
@@ -63,7 +63,7 @@ module.exports = async () => {
expect(
parseInt(request.body.version, 10),
- "Version should be a valid number"
+ "Version should be a valid number",
).to.be.a("number");
// We replace "https:" with "http:" string on CI
diff --git a/test/unit/default.test.js b/test/unit/default.test.js
index af29105e..8dc67d2d 100644
--- a/test/unit/default.test.js
+++ b/test/unit/default.test.js
@@ -1,13 +1,13 @@
-const { JSDOM } = require('jsdom');
-const fs = require('fs');
-const path = require('path');
-const vm = require('vm');
-const { expect } = require('chai');
-
-describe('default script', function () {
- it('sends pageview and event', function () {
- const dom = new JSDOM('', {
- url: 'https://example.com/'
+const { JSDOM } = require("jsdom");
+const fs = require("fs");
+const path = require("path");
+const vm = require("vm");
+const { expect } = require("chai");
+
+describe("default script", function () {
+ it("sends pageview and event", function () {
+ const dom = new JSDOM("", {
+ url: "https://example.com/",
});
const requests = [];
@@ -15,13 +15,13 @@ describe('default script', function () {
dom.window.Image = function () {
return {
set src(value) {
- requests.push({ type: 'image', url: value });
- }
+ requests.push({ type: "image", url: value });
+ },
};
};
dom.window.navigator.sendBeacon = function (url, data) {
- requests.push({ type: 'beacon', url, data });
+ requests.push({ type: "beacon", url, data });
return true;
};
@@ -33,20 +33,23 @@ describe('default script', function () {
Image: dom.window.Image,
});
- const scriptPath = path.resolve(__dirname, '../../dist/latest/latest.dev.js');
- const scriptContent = fs.readFileSync(scriptPath, 'utf8');
+ const scriptPath = path.resolve(
+ __dirname,
+ "../../dist/latest/latest.dev.js",
+ );
+ const scriptContent = fs.readFileSync(scriptPath, "utf8");
vm.runInContext(scriptContent, context);
expect(requests.length).to.be.greaterThan(0);
const pvUrl = new URL(requests[0].url);
- expect(pvUrl.pathname).to.equal('/simple.gif');
- expect(pvUrl.searchParams.get('type')).to.equal('pageview');
+ expect(pvUrl.pathname).to.equal("/simple.gif");
+ expect(pvUrl.searchParams.get("type")).to.equal("pageview");
- dom.window.sa_event('unit_test');
+ dom.window.sa_event("unit_test");
expect(requests.length).to.be.greaterThan(1);
const evUrl = new URL(requests[requests.length - 1].url);
- expect(evUrl.searchParams.get('type')).to.equal('event');
- expect(evUrl.searchParams.get('event')).to.equal('unit_test');
+ expect(evUrl.searchParams.get("type")).to.equal("event");
+ expect(evUrl.searchParams.get("event")).to.equal("unit_test");
});
});