|
| 1 | +const { JSDOM } = require("jsdom"); |
| 2 | +const { readFileSync } = require("fs"); |
| 3 | +const vm = require("vm"); |
| 4 | +const { expect } = require("chai"); |
| 5 | + |
| 6 | +describe("default script", function () { |
| 7 | + it("sends pageview, event and beacon requests", function () { |
| 8 | + const dom = new JSDOM("<!doctype html><html><body></body></html>", { |
| 9 | + url: "https://example.com/", |
| 10 | + runScripts: "outside-only", |
| 11 | + }); |
| 12 | + |
| 13 | + const sent = []; |
| 14 | + dom.window.Image = function () { |
| 15 | + return { |
| 16 | + set src(url) { |
| 17 | + sent.push({ type: "image", url }); |
| 18 | + }, |
| 19 | + }; |
| 20 | + }; |
| 21 | + dom.window.navigator.sendBeacon = function (url, data) { |
| 22 | + sent.push({ type: "beacon", url, data }); |
| 23 | + return true; |
| 24 | + }; |
| 25 | + |
| 26 | + const script = readFileSync("dist/latest/latest.dev.js", "utf8"); |
| 27 | + vm.runInContext(script, dom.getInternalVMContext()); |
| 28 | + |
| 29 | + dom.window.sa_event("unit_test"); |
| 30 | + |
| 31 | + dom.window.document.hidden = true; |
| 32 | + dom.window.document.dispatchEvent(new dom.window.Event("visibilitychange")); |
| 33 | + |
| 34 | + const gif = sent.find( |
| 35 | + (r) => r.type === "image" && /simple\.gif/.test(r.url) |
| 36 | + ); |
| 37 | + const eventReq = sent.find( |
| 38 | + (r) => r.type === "image" && /event_unit_test/.test(r.url) |
| 39 | + ); |
| 40 | + const beacon = sent.find((r) => r.type === "beacon"); |
| 41 | + |
| 42 | + expect(gif, "pageview gif request").to.exist; |
| 43 | + expect(eventReq, "event gif request").to.exist; |
| 44 | + expect(beacon, "append beacon request").to.exist; |
| 45 | + expect(beacon.url).to.match(/\/append$/); |
| 46 | + expect(beacon.data).to.include('"type":"append"'); |
| 47 | + }); |
| 48 | +}); |
0 commit comments