From 10a0cf46ddce6ed13b591f11cf0df91fbf57cd6b Mon Sep 17 00:00:00 2001 From: Tobias duelli Date: Wed, 18 Nov 2026 14:34:40 +0100 Subject: [PATCH 1/3] chore: AI ruleset and quality check AGENTS.md, rules for code conventions, code on the customer's page and tests, the edit and stop hooks, the test-writer agent, the review command, the pre-push hook, the setup script, and the quality check that judges only what a branch adds, with its CI workflow. The quality core is byte-identical to Frontend's. Co-Authored-By: Claude Opus 5.5 --- .claude/agents/test-writer.md | 14 + .claude/commands/review.md | 113 +++ .claude/hooks/check-before-stop.mjs | 38 + .claude/hooks/check-edited-file.mjs | 8 + .claude/rules/code-conventions.md | 44 ++ .claude/rules/host-page.md | 50 ++ .claude/rules/testing.md | 38 + .claude/settings.json | 29 + .githooks/install.sh | 17 + .githooks/pre-push | 52 ++ .github/workflows/quality.yml | 55 ++ AGENTS.md | 65 ++ CLAUDE.md | 1 + scripts/setup-worktree.sh | 29 + scripts/testMock.js | 1 - tools/quality/analyze.mjs | 618 +++++++++++++++ tools/quality/changes.mjs | 136 ++++ tools/quality/check.mjs | 168 ++++ tools/quality/check.test.mjs | 104 +++ tools/quality/config.mjs | 106 +++ tools/quality/core.cases.mjs | 1139 +++++++++++++++++++++++++++ tools/quality/core.sha256 | 1 + tools/quality/hooks.mjs | 193 +++++ tools/quality/measure.mjs | 78 ++ tools/quality/moves.mjs | 64 ++ tools/quality/rules.mjs | 345 ++++++++ 26 files changed, 3505 insertions(+), 1 deletion(-) create mode 100644 .claude/agents/test-writer.md create mode 100644 .claude/commands/review.md create mode 100644 .claude/hooks/check-before-stop.mjs create mode 100644 .claude/hooks/check-edited-file.mjs create mode 100644 .claude/rules/code-conventions.md create mode 100644 .claude/rules/host-page.md create mode 100644 .claude/rules/testing.md create mode 100644 .claude/settings.json create mode 100755 .githooks/install.sh create mode 100755 .githooks/pre-push create mode 100644 .github/workflows/quality.yml create mode 100644 AGENTS.md create mode 100644 CLAUDE.md create mode 100755 scripts/setup-worktree.sh delete mode 100644 scripts/testMock.js create mode 100644 tools/quality/analyze.mjs create mode 100644 tools/quality/changes.mjs create mode 100644 tools/quality/check.mjs create mode 100644 tools/quality/check.test.mjs create mode 100644 tools/quality/config.mjs create mode 100644 tools/quality/core.cases.mjs create mode 100644 tools/quality/core.sha256 create mode 100644 tools/quality/hooks.mjs create mode 100644 tools/quality/measure.mjs create mode 100644 tools/quality/moves.mjs create mode 100644 tools/quality/rules.mjs diff --git a/.claude/agents/test-writer.md b/.claude/agents/test-writer.md new file mode 100644 index 00000000..905dc813 --- /dev/null +++ b/.claude/agents/test-writer.md @@ -0,0 +1,14 @@ +--- +name: test-writer +description: Writes failing tests from a requirement before the implementation exists. Use at the start of new behaviour or a bug fix. +tools: Read, Grep, Glob, Edit, Write, Bash +--- + +You turn a requirement into tests. You do not write implementation code. The one exception: a new module may start as a file with its exported signatures throwing `not implemented`, so that the tests can import it. + +- Read the requirement, `.claude/rules/testing.md` and `.claude/rules/host-page.md`. Work from what the code must do on a customer's page, not from how it does it today. +- Write at least one test per requirement, next to the code it will test, at the level the rules name: `src/.test.js` with Vitest (a `@vitest-environment jsdom` docblock when it needs a DOM), or `smoke/*.spec.mjs` when only the built bundle in a real browser can show it. Name each test after the behaviour: `it('ignores a message from another frame')`. +- Import `describe`, `it`, `expect` and `vi` from `vitest`. Assert behaviour, not that code ran. Fake the network, time and the Messenger frame; do not mock the module under test or its helpers. +- Cover what the host page sees: no new global, no error thrown into the page, nothing sent to a frame without its target origin, masking left on. +- Run the tests with `npx vitest run ` (smoke: `npm run build`, then `npx playwright test `) and confirm they fail for the expected reason, not because of a typo or a wrong import. +- Report which test covers which requirement, and the failing output. diff --git a/.claude/commands/review.md b/.claude/commands/review.md new file mode 100644 index 00000000..15046ce5 --- /dev/null +++ b/.claude/commands/review.md @@ -0,0 +1,113 @@ +You are a strict code reviewer for the Gleap JavaScript SDK (the `gleap` package customers embed in their pages: plain JavaScript, webpack, Vitest, Playwright smoke tests). Review all changes on the current branch compared to `origin/master`. + +## Steps + +1. Run `git diff $(git merge-base HEAD origin/master)..HEAD -- src index.d.ts smoke package.json webpack.config.js babel.config.js README.md CHANGELOG.md` to get the full diff. +2. If it is empty, run the same with `git diff --cached`, then `git diff`. +3. If all diffs are empty, output "No reviewable code changes found." and stop. +4. Read `AGENTS.md` and `.claude/rules/*.md`, then check every changed file against the rules below. +5. Run `node tools/quality/check.mjs --base origin/master` and include what it reports. +6. For SSOT checks, search the codebase (Grep, Glob) for duplicate helpers, constants and message names, the Server (`../Server`, from a worktree `../../Server`) for values it stores, and the Messenger (`../Messenger-App`) for message names it sends or reads. +7. For every non-formatting change, read the surrounding code, not only the diff, and judge whether existing behaviour could break on a customer's page. + +## Review output format + +Structure the review exactly like this. If everything passes, one line per topic with a checkmark; details only where something is wrong. + +``` +### Overview +_1-2 sentences on what the changes do._ + +### Checklist + +✅ SSOT +✅ Code conventions +✅ Public API and compatibility +✅ Host page: globals, teardown, errors +✅ CSP and Trusted Types +✅ Frames and messages +✅ Privacy +✅ Load time, size and browsers +✅ Tests +✅ Over-engineering +✅ Dead code +✅ Impact & Risk +``` + +- One line per topic. ✅ = clean, ❌ = issue found, with a reason of at most ~10 words. +- Below the checklist, output only the sections that have findings: + +``` +### Critical Issues (must fix before merge) + +> **[Rule]** [GleapThing.js:42](src/GleapThing.js#L42) +> What is wrong and why it matters. +> **Fix:** Concrete suggestion. + +### Warnings + +> **[Rule]** [GleapThing.js:10](src/GleapThing.js#L10) +> Short explanation. + +### Impact & Risk Analysis + +> **Risk:** `sendMessage()` is called from 9 places. The new early return drops queued messages when the frame reloads. + +--- + +### Confidence: X/5 +``` + +If the score is below 5, say why. 5: every rule verified with searches, all usages traced. 4: minor gaps in tracing. 3: some checks limited. 2: files skimmed. 1: superficial. + +Do not output suggestions for nice-to-haves, praise, or formatting-only changes. + +## Rules to check + +### 1. SSOT (critical) + +For every new helper, constant or message name: search for an existing one. Flag a duplicate of an existing helper (the table in `.claude/rules/code-conventions.md`), a value the Server stores spelled differently from the Server, and a message name that differs from what the Messenger sends or reads. + +### 2. Code conventions + +Everything in `.claude/rules/code-conventions.md`, including the one-job-one-system table. Critical: a new runtime package (in `dependencies` or imported), new logic added to a file already over its limit instead of its own module. + +### 3. Public API and compatibility (critical) + +Flag a removed or renamed `Gleap.*` method, parameter, option, default, callback, event, custom element, cookie or storage key; a changed meaning without a major version; an API change without `index.d.ts`, `CHANGELOG.md` and, for a new call, `README.md`; new behaviour that existing projects get without opting in; a third positional parameter on a public method. + +### 4. Host page: globals, teardown, errors (critical) + +Flag a new `window.*` property, a change to a built-in prototype, a polyfill; a listener, observer, timer or frame without a teardown; a non-passive scroll, touch or wheel listener; a wrapper of `fetch`, XHR or `console` that drops `this` or arguments, can throw, or restores unconditionally; a public method or customer callback that can throw into the page. + +### 5. CSP and Trusted Types (critical) + +Flag `eval`, `new Function` or string timers; a ` +${scriptTag}`, +}); + +// The host page and the bundle are served here; everything else (the Gleap API, the messenger) is aborted. +const servePage = async (page, { csp, scriptTag = `` } = {}) => { + const problems = []; + page.on('pageerror', (error) => problems.push(`pageerror: ${error.message}`)); + page.on('console', (message) => { + if (message.type() === 'error' && !message.text().startsWith('Failed to load resource')) problems.push(`console.error: ${message.text()}`); + }); + await page.route('**/*', (route) => { + const url = new URL(route.request().url()); + if (url.origin !== HOST) return route.abort(); + if (url.pathname === '/sdk.js') return route.fulfill({ path: BROWSER_BUNDLE, contentType: 'text/javascript' }); + if (url.pathname === '/sdk.mjs') return route.fulfill({ path: ESM_BUNDLE, contentType: 'text/javascript' }); + return route.fulfill(hostPage({ csp, scriptTag })); + }); + await page.goto(`${HOST}/`); + return problems; +}; + +test('the CDN bundle defines window.Gleap and nothing else, without an error', async ({ page }) => { + const problems = await servePage(page); + + const added = await page.evaluate(() => Object.keys(window).filter((key) => !window.__keysBefore.includes(key))); + expect(added).toEqual(['Gleap']); + expect(problems).toEqual([]); +}); + +test('every function index.d.ts declares exists on window.Gleap', async ({ page }) => { + await servePage(page); + + const missing = await page.evaluate((names) => names.filter((name) => typeof window.Gleap[name] !== 'function'), declaredFunctions()); + expect(missing).toEqual(DECLARED_BUT_MISSING); +}); + +test('initialize under a strict nonce CSP that allows the Gleap hosts, with them unreachable: no violation, no page error', async ({ page }) => { + const gleap = 'https://*.gleap.io wss://*.gleap.io'; + const csp = `default-src 'none'; script-src 'nonce-${NONCE}' 'strict-dynamic'; style-src 'nonce-${NONCE}'; img-src 'self' data: ${gleap}; connect-src 'self' ${gleap}; frame-src 'self' ${gleap}`; + const problems = await servePage(page, { csp }); + + const sessionFailed = page.waitForEvent('requestfailed', (request) => request.url().startsWith('https://api.gleap.io/')); + await page.evaluate(() => window.Gleap.initialize('smoke-test-project')); + await sessionFailed; + // One frame later the SDK has handled the failure. + await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(resolve))); + + expect(await page.evaluate(() => window.__violations)).toEqual([]); + expect(problems.filter((problem) => problem.startsWith('pageerror'))).toEqual([]); +}); + +test('the ESM bundle exports the same Gleap as the CDN bundle', async ({ page }) => { + await servePage(page, { + scriptTag: ` +`, + }); + + await page.waitForFunction(() => window.__esm); + const [esm, cdn] = await page.evaluate(() => [window.__esm, Object.getOwnPropertyNames(window.Gleap).sort()]); + expect(esm).toEqual(cdn); +}); + +test('the npm entry points load in Node without a DOM, as in server-side rendering', async () => { + const require = createRequire(import.meta.url); + const commonJs = require(`${ROOT}build/cjs/index.js`); + const { default: esm } = await import(ESM_BUNDLE); + + expect(typeof commonJs.initialize).toBe('function'); + expect(typeof esm.initialize).toBe('function'); +}); diff --git a/src/GleapAdminOrigins.test.js b/src/GleapAdminOrigins.test.js index 323710db..f3149901 100644 --- a/src/GleapAdminOrigins.test.js +++ b/src/GleapAdminOrigins.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import GleapAdminManager from './GleapAdminManager'; import { GLEAP_ADMIN_ORIGINS, @@ -39,7 +40,8 @@ describe('admin origin allowlist', () => { expect(isGleapAdminOrigin('https://app.gleap.io')).toBe(true); }); - it.each(LOOKALIKES)('rejects %p', (origin) => { + // As objects: a title takes an array row apart into its items, so the array origin would read like a real one. + it.each(LOOKALIKES.map((origin) => ({ origin })))('rejects $origin', ({ origin }) => { expect(isGleapAdminOrigin(origin)).toBe(false); expect(resolveGleapAdminOrigin(origin)).toBe(GLEAP_DEFAULT_ADMIN_ORIGIN); }); @@ -64,11 +66,11 @@ describe('GleapAdminManager message origin', () => { GleapAdminManager.instance = undefined; manager = GleapAdminManager.getInstance(); // Keep the admin UI side effects out of the origin check. - manager.initAdminHelper = jest.fn(() => manager.injectFrame()); - manager.startPageListener = jest.fn(); + manager.initAdminHelper = vi.fn(() => manager.injectFrame()); + manager.startPageListener = vi.fn(); listeners = []; const add = window.addEventListener.bind(window); - jest.spyOn(window, 'addEventListener').mockImplementation((type, fn, opts) => { + vi.spyOn(window, 'addEventListener').mockImplementation((type, fn, opts) => { if (type === 'message') listeners.push(fn); return add(type, fn, opts); }); @@ -77,7 +79,7 @@ describe('GleapAdminManager message origin', () => { afterEach(() => { listeners.forEach((fn) => window.removeEventListener('message', fn)); - jest.restoreAllMocks(); + vi.restoreAllMocks(); }); it.each(['https://app.gleap.ai.evil.com', 'https://evilgleap.ai', 'https://example.com'])( diff --git a/src/GleapAiChatbarManager.test.js b/src/GleapAiChatbarManager.test.js index 1e82fa1a..c07b1d7f 100644 --- a/src/GleapAiChatbarManager.test.js +++ b/src/GleapAiChatbarManager.test.js @@ -1,26 +1,27 @@ +import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest'; import { GleapFrameManager, GleapSession, GleapTabCommunication } from './Gleap'; import GleapAiChatbarManager from './GleapAiChatbarManager'; // Keep the barrel + helper imports light (no DOM bootstrap, no SDK_VERSION global). // The manager only reaches for GleapSession/GleapTabCommunication on the paths under // test here; the other managers just need to exist so the module resolves. -jest.mock('./Gleap', () => ({ - GleapFrameManager: { getInstance: jest.fn(() => ({})) }, - GleapConfigManager: { getInstance: jest.fn(() => ({ getFlowConfig: () => ({}) })) }, - GleapSession: { getInstance: jest.fn() }, - GleapEventManager: { notifyEvent: jest.fn() }, - GleapTranslationManager: { getInstance: jest.fn(() => ({ getOverrideLanguage: () => null })) }, - GleapTabCommunication: { getInstance: jest.fn() }, +vi.mock('./Gleap', () => ({ + GleapFrameManager: { getInstance: vi.fn(() => ({})) }, + GleapConfigManager: { getInstance: vi.fn(() => ({ getFlowConfig: () => ({}) })) }, + GleapSession: { getInstance: vi.fn() }, + GleapEventManager: { notifyEvent: vi.fn() }, + GleapTranslationManager: { getInstance: vi.fn(() => ({ getOverrideLanguage: () => null })) }, + GleapTabCommunication: { getInstance: vi.fn() }, })); -jest.mock('./GleapAgentToolManager', () => ({ +vi.mock('./GleapAgentToolManager', () => ({ __esModule: true, - default: { getInstance: jest.fn(() => ({ getAgentTools: () => [] })) }, + default: { getInstance: vi.fn(() => ({ getAgentTools: () => [] })) }, })); -jest.mock('./GleapHelper', () => ({ - bootstrapGleapFrame: jest.fn(), - runFunctionWhenDomIsReady: jest.fn(), +vi.mock('./GleapHelper', () => ({ + bootstrapGleapFrame: vi.fn(), + runFunctionWhenDomIsReady: vi.fn(), })); let sendMessageMock; @@ -28,7 +29,7 @@ let messageHandler; // the window 'message' listener registered by _listenForMes // A fake chatbar iframe whose contentWindow captures every posted message. const attachReadyFrame = (manager) => { - const contentWindow = { postMessage: jest.fn() }; + const contentWindow = { postMessage: vi.fn() }; manager.chatbarFrame = { contentWindow }; manager.comReady = true; return contentWindow; @@ -46,13 +47,13 @@ beforeEach(() => { // constructor's _listenForMessages / _listenForOutsideClicks, capturing the // 'message' handler so we can simulate inbound frame messages. global.window = { - addEventListener: jest.fn((type, handler) => { + addEventListener: vi.fn((type, handler) => { if (type === 'message') messageHandler = handler; }), }; - global.document = { addEventListener: jest.fn() }; + global.document = { addEventListener: vi.fn() }; - sendMessageMock = jest.fn(); + sendMessageMock = vi.fn(); GleapTabCommunication.getInstance.mockReturnValue({ sendMessage: sendMessageMock }); GleapSession.getInstance.mockReturnValue({ session: { gleapId: 'user-1' } }); @@ -164,7 +165,7 @@ describe('inbound chatbar-notification-read (from the frame)', () => { attachReadyFrame(manager); messageHandler({ - source: { postMessage: jest.fn() }, // some other window + source: { postMessage: vi.fn() }, // some other window data: JSON.stringify({ name: 'chatbar-notification-read' }), }); diff --git a/src/GleapBannerManager.test.js b/src/GleapBannerManager.test.js index 3c2f7320..99b20fe0 100644 --- a/src/GleapBannerManager.test.js +++ b/src/GleapBannerManager.test.js @@ -1,22 +1,23 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest'; import GleapBannerManager, { bodyClipsInlineBanner, closedBannerEventName } from './GleapBannerManager'; -const mockUrlHandler = jest.fn(); -const mockLogEvent = jest.fn(); -const mockStreamEvents = jest.fn(); +const mockUrlHandler = vi.fn(); +const mockLogEvent = vi.fn(); +const mockStreamEvents = vi.fn(); const mockSession = { session: { gleapId: 'gleap-1' } }; -jest.mock('./Gleap', () => ({ +vi.mock('./Gleap', () => ({ __esModule: true, default: {}, - GleapFrameManager: { getInstance: jest.fn(() => ({ urlHandler: mockUrlHandler })) }, - GleapSession: { getInstance: jest.fn(() => mockSession) }, - GleapStreamedEvent: { getInstance: jest.fn(() => ({ logEvent: mockLogEvent, streamEvents: mockStreamEvents })) }, + GleapFrameManager: { getInstance: vi.fn(() => ({ urlHandler: mockUrlHandler })) }, + GleapSession: { getInstance: vi.fn(() => mockSession) }, + GleapStreamedEvent: { getInstance: vi.fn(() => ({ logEvent: mockLogEvent, streamEvents: mockStreamEvents })) }, })); -jest.mock('./GleapHelper', () => ({ - bootstrapGleapFrame: jest.fn(), +vi.mock('./GleapHelper', () => ({ + bootstrapGleapFrame: vi.fn(), })); const style = (overflowX, overflowY = overflowX) => ({ overflowX, overflowY }); diff --git a/src/GleapCSPNonce.test.js b/src/GleapCSPNonce.test.js index d3cb899f..2ac4c083 100644 --- a/src/GleapCSPNonce.test.js +++ b/src/GleapCSPNonce.test.js @@ -1,16 +1,14 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, test, expect, vi, afterEach } from 'vitest'; // The nonce is auto-detected at module-evaluation time (document.currentScript is only // readable then), so every detection test has to require the module with the DOM already // in the state under test — hence the isolated re-require instead of a top-level import. -const loadHelper = () => { - let helper; - jest.isolateModules(() => { - helper = require('./GleapHelper'); - }); - return helper; +const loadHelper = async () => { + vi.resetModules(); + return import('./GleapHelper'); }; const addSdkScript = (nonce, { hideAttribute = false } = {}) => { @@ -35,12 +33,12 @@ const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); // bootstrapGleapFrame writes into iframe.contentDocument. Replacing it with a spy is what // lets us assert on the exact markup — the whole point of the fix is what lands in there. const bootstrapAndCaptureMarkup = async (helper, html, url = 'https://messenger-app.gleap.io/') => { - const writtenDoc = { open: jest.fn(), write: jest.fn(), close: jest.fn() }; + const writtenDoc = { open: vi.fn(), write: vi.fn(), close: vi.fn() }; const iframe = document.createElement('iframe'); document.body.appendChild(iframe); Object.defineProperty(iframe, 'contentDocument', { value: writtenDoc, configurable: true }); - global.fetch = jest.fn(() => Promise.resolve({ ok: true, text: () => Promise.resolve(html) })); + global.fetch = vi.fn(() => Promise.resolve({ ok: true, text: () => Promise.resolve(html) })); helper.bootstrapGleapFrame(iframe, url); await flush(); @@ -52,49 +50,49 @@ afterEach(() => { document.head.innerHTML = ''; document.body.innerHTML = ''; delete global.fetch; - jest.restoreAllMocks(); + vi.restoreAllMocks(); }); describe('CSP nonce detection from the SDK script tag', () => { - test('picks up the nonce so a correctly-nonced loader needs no configuration', () => { + test('picks up the nonce so a correctly-nonced loader needs no configuration', async () => { addSdkScript('r4nd0m123'); - expect(loadHelper().getGleapCSPNonce()).toBe('r4nd0m123'); + expect((await loadHelper()).getGleapCSPNonce()).toBe('r4nd0m123'); }); // Regression: reading getAttribute('nonce') first returns "" on exactly the strict-CSP // pages this feature exists for, because browsers hide the content attribute. - test('still detects the nonce when the content attribute is hidden', () => { + test('still detects the nonce when the content attribute is hidden', async () => { addSdkScript('hidden-nonce-value', { hideAttribute: true }); - expect(loadHelper().getGleapCSPNonce()).toBe('hidden-nonce-value'); + expect((await loadHelper()).getGleapCSPNonce()).toBe('hidden-nonce-value'); }); - test('is null when the SDK tag carries no nonce', () => { + test('is null when the SDK tag carries no nonce', async () => { addSdkScript(undefined); - expect(loadHelper().getGleapCSPNonce()).toBeNull(); + expect((await loadHelper()).getGleapCSPNonce()).toBeNull(); }); - test('is null when there is no SDK tag at all', () => { - expect(loadHelper().getGleapCSPNonce()).toBeNull(); + test('is null when there is no SDK tag at all', async () => { + expect((await loadHelper()).getGleapCSPNonce()).toBeNull(); }); }); describe('setGleapCSPNonce', () => { - test('overrides the auto-detected nonce', () => { + test('overrides the auto-detected nonce', async () => { addSdkScript('detected'); - const helper = loadHelper(); + const helper = await loadHelper(); helper.setGleapCSPNonce('configured'); expect(helper.getGleapCSPNonce()).toBe('configured'); }); - test('falls back to the detected nonce when passed a rejected value', () => { + test('falls back to the detected nonce when passed a rejected value', async () => { addSdkScript('detected'); - const helper = loadHelper(); + const helper = await loadHelper(); helper.setGleapCSPNonce(null); expect(helper.getGleapCSPNonce()).toBe('detected'); }); - test('trims surrounding whitespace', () => { - const helper = loadHelper(); + test('trims surrounding whitespace', async () => { + const helper = await loadHelper(); helper.setGleapCSPNonce(' spaced-nonce '); expect(helper.getGleapCSPNonce()).toBe('spaced-nonce'); }); @@ -105,17 +103,17 @@ describe('setGleapCSPNonce', () => { ['a space-separated injection', 'abc onload=alert(1)'], ['a non-string', { nonce: 'abc' }], ['an empty string', ''], - ])('rejects %s', (_label, value) => { - const helper = loadHelper(); + ])('rejects %s', async (_label, value) => { + const helper = await loadHelper(); helper.setGleapCSPNonce(value); expect(helper.getGleapCSPNonce()).toBeNull(); }); }); describe('applyGleapCSPNonce', () => { - test('sets both the attribute and the IDL property on a created '); }); @@ -179,7 +177,7 @@ describe('bootstrapGleapFrame — nonce stamping on the written document', () => test('still sets the SPA route before the app bundle runs', async () => { addSdkScript('order-nonce'); const { markup } = await bootstrapAndCaptureMarkup( - loadHelper(), + await loadHelper(), APP_HTML, 'https://messenger-app.gleap.io/conversation' ); @@ -191,7 +189,7 @@ describe('bootstrapGleapFrame — nonce stamping on the written document', () => test('does not double-stamp a tag that already carries a nonce', async () => { addSdkScript('dedupe-nonce'); const { markup } = await bootstrapAndCaptureMarkup( - loadHelper(), + await loadHelper(), '' ); @@ -201,14 +199,14 @@ describe('bootstrapGleapFrame — nonce stamping on the written document', () => // Non-CSP pages are the overwhelming majority — they must keep byte-identical markup. test('writes unchanged markup when there is no nonce', async () => { - const { markup } = await bootstrapAndCaptureMarkup(loadHelper(), APP_HTML); + const { markup } = await bootstrapAndCaptureMarkup(await loadHelper(), APP_HTML); expect(markup).not.toContain('nonce'); expect(markup).toContain(''; - global.fetch = jest.fn(() => Promise.resolve({ ok: true, text: () => Promise.resolve(html) })); + global.fetch = vi.fn(() => Promise.resolve({ ok: true, text: () => Promise.resolve(html) })); helper.bootstrapGleapFrame(iframe, 'https://messenger-app.gleap.io/'); await flush(); return { writtenDoc, violationListener: listeners['securitypolicyviolation'] }; }; test('a CSP violation inside the bootstrapped frame is surfaced with URI and directive', async () => { - const warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); - const helper = loadHelper(); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const helper = await loadHelper(); const { writtenDoc, violationListener } = await bootstrapAndCaptureViolationListener(helper); @@ -323,8 +321,8 @@ describe('bootstrapGleapFrame — CSP/network failure diagnostics', () => { }); test('duplicate violations warn once; Report-Only violations stay silent', async () => { - const warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); - const helper = loadHelper(); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const helper = await loadHelper(); const { violationListener } = await bootstrapAndCaptureViolationListener(helper); diff --git a/src/GleapCaptureLogs.test.js b/src/GleapCaptureLogs.test.js index edde2049..606d26dd 100644 --- a/src/GleapCaptureLogs.test.js +++ b/src/GleapCaptureLogs.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, test, expect, vi, beforeEach } from 'vitest'; // Background log collection sends only what a bug report carries, only what the request asks for, // and nothing when the app switched it off (Gleap.setRemoteLogCollectionEnabled(false)). @@ -9,9 +10,9 @@ const mockFlowConfig = { enableWebReplays: true, capture: {} }; const mockReplay = { startDate: 1, events: [{ type: 4, data: { href: 'https://app.test' } }], packed: false, type: 'rrweb' }; const iso = (ms) => new Date(ms).toISOString(); -jest.mock('./Gleap', () => ({ +vi.mock('./Gleap', () => ({ __esModule: true, - default: { openConversation: jest.fn(), open: jest.fn() }, + default: { openConversation: vi.fn(), open: vi.fn() }, GleapConfigManager: { getInstance: () => ({ getFlowConfig: () => mockFlowConfig, onConfigLoaded: (callback) => callback() }), }, @@ -39,7 +40,7 @@ jest.mock('./Gleap', () => ({ getInstance: () => ({ session: { gleapId: 'g1' }, sdkKey: 'key', apiUrl: 'https://api.test', injectSession: () => {} }), }, GleapFrameManager: { - getInstance: () => ({ sendMessage: jest.fn(), setCaptureHidden: jest.fn(), setCaptureEditorOpen: jest.fn() }), + getInstance: () => ({ sendMessage: vi.fn(), setCaptureHidden: vi.fn(), setCaptureEditorOpen: vi.fn() }), }, GleapTranslationManager: { getInstance: () => ({ isRTLLayout: false }) }, })); @@ -135,21 +136,21 @@ describe('log requests from the websocket', () => { const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); - beforeEach(() => { - jest.resetModules(); - jest.doMock('./GleapCaptureApi', () => { - const actual = jest.requireActual('./GleapCaptureApi'); + beforeEach(async () => { + vi.resetModules(); + vi.doMock('./GleapCaptureApi', async (importOriginal) => { + const actual = await importOriginal(); return { ...actual, - claimCaptureRequest: jest.fn(() => Promise.resolve({ status: 200, data: { claimedElsewhere: false } })), - postCaptureLogs: jest.fn(() => Promise.resolve({ status: 200, data: {} })), - reportCaptureEvent: jest.fn(() => Promise.resolve({ status: 200, data: {} })), + claimCaptureRequest: vi.fn(() => Promise.resolve({ status: 200, data: { claimedElsewhere: false } })), + postCaptureLogs: vi.fn(() => Promise.resolve({ status: 200, data: {} })), + reportCaptureEvent: vi.fn(() => Promise.resolve({ status: 200, data: {} })), }; }); - api = require('./GleapCaptureApi'); - const settings = require('./GleapCaptureSettings'); + api = await import('./GleapCaptureApi'); + const settings = await import('./GleapCaptureSettings'); settings.setRemoteLogCollectionEnabled(true); - manager = new (require('./GleapCaptureManager').default)(); + manager = new (await import('./GleapCaptureManager')).default(); mockFlowConfig.capture = {}; }); @@ -170,7 +171,7 @@ describe('log requests from the websocket', () => { }); test('switched off by the app: answered "unsupported", nothing collected', async () => { - require('./GleapCaptureSettings').setRemoteLogCollectionEnabled(false); + (await import('./GleapCaptureSettings')).setRemoteLogCollectionEnabled(false); manager.handleServerRequest(request('cr-2')); await flush(); @@ -197,7 +198,7 @@ describe('log requests from the websocket', () => { }); test('logs along with a screenshot or recording: none when the app switched log collection off', async () => { - const settings = require('./GleapCaptureSettings'); + const settings = await import('./GleapCaptureSettings'); const session = { options: { attachLogs: true } }; settings.setRemoteLogCollectionEnabled(false); diff --git a/src/GleapCaptureMasking.test.js b/src/GleapCaptureMasking.test.js index ecde78eb..8d1e70df 100644 --- a/src/GleapCaptureMasking.test.js +++ b/src/GleapCaptureMasking.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, test, expect, vi, beforeAll, afterAll } from 'vitest'; // What capture requests must keep private: the black boxes painted over screenshots, and the page // recording (rrweb) used where there is no screen capture. Both follow the rules bug reports use @@ -8,11 +9,11 @@ const mockReplayRecorder = { customOptions: {}, - pauseForCapture: jest.fn(() => false), - resumeAfterCapture: jest.fn(), + pauseForCapture: vi.fn(() => false), + resumeAfterCapture: vi.fn(), }; -jest.mock('./Gleap', () => ({ +vi.mock('./Gleap', () => ({ __esModule: true, default: {}, GleapNetworkIntercepter: { getInstance: () => ({ getRequests: () => [], stopped: false, setStopped: () => {} }) }, diff --git a/src/GleapClickListener.test.js b/src/GleapClickListener.test.js index 4d9b9767..d264c7df 100644 --- a/src/GleapClickListener.test.js +++ b/src/GleapClickListener.test.js @@ -1,31 +1,30 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, expect, vi, beforeEach } from 'vitest'; // GleapClickListener pulls the frame/console managers in from the main Gleap module, // which drags in the whole SDK — mock it so the listener can be tested on its own. -const mockHandleGleapLink = jest.fn(); -const mockAddLog = jest.fn(); -const mockIsOpened = jest.fn(() => true); +const mockHandleGleapLink = vi.fn(); +const mockAddLog = vi.fn(); +const mockIsOpened = vi.fn(() => true); -jest.mock('./Gleap', () => ({ +vi.mock('./Gleap', () => ({ handleGleapLink: (...args) => mockHandleGleapLink(...args), GleapConsoleLogManager: { getInstance: () => ({ addLog: mockAddLog }) }, GleapFrameManager: { getInstance: () => ({ isOpened: mockIsOpened }) }, })); -jest.mock('./GleapHelper', () => ({ +vi.mock('./GleapHelper', () => ({ getDOMElementDescription: () => 'element', })); const CHECKLIST_LINK = 'gleap://checklist/6739f47e013864770e120adf'; -const startListener = () => { - let GleapClickListener; - jest.isolateModules(() => { - GleapClickListener = require('./GleapClickListener').default; - }); - // The singleton is per-module-registry, so isolateModules gives a fresh one each time. +const startListener = async () => { + vi.resetModules(); + const { default: GleapClickListener } = await import('./GleapClickListener'); + // The singleton is per-module-registry, so a fresh registry gives a fresh one each time. GleapClickListener.getInstance().start(); }; @@ -42,9 +41,9 @@ describe('GleapClickListener gleap:// links', () => { mockAddLog.mockClear(); }); - it('handles a click directly on the anchor', () => { + it('handles a click directly on the anchor', async () => { document.body.innerHTML = `Start checklist`; - startListener(); + await startListener(); const event = clickAndCapture(document.getElementById('link')); @@ -52,11 +51,11 @@ describe('GleapClickListener gleap:// links', () => { expect(event.defaultPrevented).toBe(true); }); - it('handles a click on a formatted child inside the anchor', () => { + it('handles a click on a formatted child inside the anchor', async () => { // Rich-text editors wrap link text in /, so the click target is // the child, not the anchor itself. document.body.innerHTML = `Start checklist`; - startListener(); + await startListener(); const event = clickAndCapture(document.getElementById('child')); @@ -64,18 +63,18 @@ describe('GleapClickListener gleap:// links', () => { expect(event.defaultPrevented).toBe(true); }); - it('handles a click on a deeply nested icon inside the anchor', () => { + it('handles a click on a deeply nested icon inside the anchor', async () => { document.body.innerHTML = `go`; - startListener(); + await startListener(); clickAndCapture(document.getElementById('icon')); expect(mockHandleGleapLink).toHaveBeenCalledWith(CHECKLIST_LINK); }); - it('ignores anchors that are not gleap:// links', () => { + it('ignores anchors that are not gleap:// links', async () => { document.body.innerHTML = `Normal link`; - startListener(); + await startListener(); const event = clickAndCapture(document.getElementById('link')); @@ -83,9 +82,9 @@ describe('GleapClickListener gleap:// links', () => { expect(event.defaultPrevented).toBe(false); }); - it('ignores clicks outside of any anchor', () => { + it('ignores clicks outside of any anchor', async () => { document.body.innerHTML = `
Just text
`; - startListener(); + await startListener(); clickAndCapture(document.getElementById('plain')); diff --git a/src/GleapCopilotTours.test.js b/src/GleapCopilotTours.test.js index 2a1d75aa..c2cc635b 100644 --- a/src/GleapCopilotTours.test.js +++ b/src/GleapCopilotTours.test.js @@ -1,23 +1,24 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, expect, vi, beforeEach } from 'vitest'; import GleapCopilotTours, { getJoinedIndicatorPositionClass } from './GleapCopilotTours'; // Stub the barrel so the real GleapCopilotTours loads without the rest of the SDK. -jest.mock('./Gleap', () => ({ +vi.mock('./Gleap', () => ({ __esModule: true, default: {}, GleapConfigManager: { - getInstance: jest.fn(() => ({ flowConfig: { color: '#485BFF' } })), + getInstance: vi.fn(() => ({ flowConfig: { color: '#485BFF' } })), }, - GleapTranslationManager: { translateText: jest.fn((key) => key) }, + GleapTranslationManager: { translateText: vi.fn((key) => key) }, })); -jest.mock('./GleapHelper', () => ({ applyGleapCSPNonce: jest.fn() })); -jest.mock('./GleapInputFiller', () => ({ typeIntoElement: jest.fn() })); -jest.mock('./UI', () => ({ - calculateContrast: jest.fn(() => '#ffffff'), - loadIcon: jest.fn(() => ''), +vi.mock('./GleapHelper', () => ({ applyGleapCSPNonce: vi.fn() })); +vi.mock('./GleapInputFiller', () => ({ typeIntoElement: vi.fn() })); +vi.mock('./UI', () => ({ + calculateContrast: vi.fn(() => '#ffffff'), + loadIcon: vi.fn(() => ''), })); const localStorageKey = 'gleap-tour-data'; @@ -43,12 +44,12 @@ const installAudioDouble = () => { createdAudioSources = []; playBehaviour = 'resolve'; - window.Audio = jest.fn(function (src) { + window.Audio = vi.fn(function (src) { createdAudioSources.push(src); this.muted = false; - this.pause = jest.fn(); - this.addEventListener = jest.fn(); - this.play = jest.fn(() => { + this.pause = vi.fn(); + this.addEventListener = vi.fn(); + this.play = vi.fn(() => { if (playBehaviour === 'reject') return Promise.reject(new DOMException('blocked', 'NotAllowedError')); if (playBehaviour === 'never') return new Promise(() => {}); return Promise.resolve(); @@ -67,7 +68,7 @@ const newTour = (config = buildConfig(), tourId = 'tour-1') => { // start() awaits the autoplay probe (a real promise) before touching the DOM, so let the // microtask queue drain between advancing the fake timers. const flush = async (ms = 0) => { - if (ms > 0) jest.advanceTimersByTime(ms); + if (ms > 0) vi.advanceTimersByTime(ms); await Promise.resolve(); await Promise.resolve(); }; @@ -78,8 +79,8 @@ beforeEach(() => { document.head.innerHTML = ''; installAudioDouble(); // jsdom implements neither, and the pointer positioning calls both. - window.scrollTo = jest.fn(); - Element.prototype.scrollIntoView = jest.fn(); + window.scrollTo = vi.fn(); + Element.prototype.scrollIntoView = vi.fn(); }); describe('audio state across page changes', () => { @@ -108,7 +109,7 @@ describe('audio state across page changes', () => { }); it('stays muted after a page change instead of asking the browser again', async () => { - jest.useFakeTimers(); + vi.useFakeTimers(); localStorage.setItem(localStorageKey, JSON.stringify({ tourId: 'tour-1', audioMuted: true })); const tours = newTour(); @@ -118,11 +119,11 @@ describe('audio state across page changes', () => { expect(tours.audioMuted).toBe(true); // The autoplay probe would have unmuted the tour - it must not run on a resume. expect(window.Audio).not.toHaveBeenCalled(); - jest.useRealTimers(); + vi.useRealTimers(); }); it('does not re-prompt with the unmute modal after a page change', async () => { - jest.useFakeTimers(); + vi.useFakeTimers(); localStorage.setItem(localStorageKey, JSON.stringify({ tourId: 'tour-1', audioMuted: true })); const tours = newTour(buildConfig({ showUnmuteModal: true })); @@ -130,11 +131,11 @@ describe('audio state across page changes', () => { await flush(); expect(document.querySelector('.gleap-audio-unmute-modal')).toBeNull(); - jest.useRealTimers(); + vi.useRealTimers(); }); it('falls back to the autoplay probe on a fresh start', async () => { - jest.useFakeTimers(); + vi.useFakeTimers(); playBehaviour = 'reject'; const tours = newTour(); @@ -142,13 +143,13 @@ describe('audio state across page changes', () => { await flush(); expect(tours.audioMuted).toBe(true); - jest.useRealTimers(); + vi.useRealTimers(); }); }); describe('autoplay probe', () => { it('starts the tour even when play() never settles', async () => { - jest.useFakeTimers(); + vi.useFakeTimers(); playBehaviour = 'never'; const tours = newTour(); @@ -157,13 +158,13 @@ describe('autoplay probe', () => { expect(tours.audioMuted).toBe(false); expect(document.getElementById('copilot-joined-container')).not.toBeNull(); - jest.useRealTimers(); + vi.useRealTimers(); }); }); describe('read text aloud', () => { it('skips the stored voice clip when the setting is off', async () => { - jest.useFakeTimers(); + vi.useFakeTimers(); const tours = newTour(buildConfig({ playVoice: false })); tours.audioMuted = false; tours.setupCopilotTour(); @@ -172,11 +173,11 @@ describe('read text aloud', () => { await flush(100); expect(createdAudioSources).not.toContain('https://example.com/1.mp3'); - jest.useRealTimers(); + vi.useRealTimers(); }); it('plays the stored voice clip when the setting is on', async () => { - jest.useFakeTimers(); + vi.useFakeTimers(); const tours = newTour(); tours.audioMuted = false; tours.setupCopilotTour(); @@ -185,13 +186,13 @@ describe('read text aloud', () => { await flush(100); expect(createdAudioSources).toContain('https://example.com/1.mp3'); - jest.useRealTimers(); + vi.useRealTimers(); }); }); describe('step message flattening', () => { const bubbleText = async (message) => { - jest.useFakeTimers(); + vi.useFakeTimers(); const tours = newTour(buildConfig({ steps: [{ selector: '', message, type: 'post', mode: 'BUTTON' }] })); tours.setupCopilotTour(); @@ -199,7 +200,7 @@ describe('step message flattening', () => { await flush(100); const text = document.getElementById('copilot-info-bubble-content').textContent; - jest.useRealTimers(); + vi.useRealTimers(); return text; }; @@ -269,7 +270,7 @@ describe('joined indicator position', () => { }); it('pins the indicator top-right when the tour config has no position', async () => { - jest.useFakeTimers(); + vi.useFakeTimers(); const tours = newTour(); tours.start(); @@ -277,11 +278,11 @@ describe('joined indicator position', () => { const indicator = document.getElementById('copilot-joined-container'); expect(positionClasses(indicator)).toEqual(['copilot-joined-container--top-right']); - jest.useRealTimers(); + vi.useRealTimers(); }); it('pins the indicator to the configured corner', async () => { - jest.useFakeTimers(); + vi.useFakeTimers(); const tours = newTour(buildConfig({ joinedIndicatorPosition: 'BOTTOM_LEFT' })); tours.start(); @@ -292,6 +293,6 @@ describe('joined indicator position', () => { expect(document.getElementById('copilot-tour-styles').textContent).toContain( '.copilot-joined-container--bottom-left {', ); - jest.useRealTimers(); + vi.useRealTimers(); }); }); diff --git a/src/GleapFeedback.test.js b/src/GleapFeedback.test.js index 01dfb330..7072784a 100644 --- a/src/GleapFeedback.test.js +++ b/src/GleapFeedback.test.js @@ -1,3 +1,4 @@ +import { describe, test, expect, vi, beforeEach } from 'vitest'; import GleapFeedback from './GleapFeedback'; import { startScreenCapture } from './ScreenCapture'; import { GleapScreenRecorder } from './GleapScreenRecorder'; @@ -10,12 +11,12 @@ const REPLAY_OPTIONS = { maskAllInputs: true }; // The SDK's global data; tests add to it (reset in beforeEach). const mockGlobalData = {}; -jest.mock('./Gleap', () => { - const manager = (methods) => ({ getInstance: jest.fn(() => methods) }); +vi.mock('./Gleap', () => { + const manager = (methods) => ({ getInstance: vi.fn(() => methods) }); return { __esModule: true, default: { - getInstance: jest.fn(() => ({ + getInstance: vi.fn(() => ({ getGlobalDataItem: (key) => mockGlobalData[key] ?? null, setGlobalDataItem: (key, value) => { mockGlobalData[key] = value; @@ -25,7 +26,7 @@ jest.mock('./Gleap', () => { }, GleapConsoleLogManager: manager({ getLogs: () => [{ log: 'hello' }] }), GleapStreamedEvent: manager({ getEventArray: () => [] }), - GleapSession: manager({ apiUrl: 'https://api.gleap.io', injectSession: jest.fn() }), + GleapSession: manager({ apiUrl: 'https://api.gleap.io', injectSession: vi.fn() }), GleapCustomDataManager: manager({ getCustomData: () => ({}), getTicketAttributes: () => ({}) }), GleapMetaDataManager: manager({ getMetaData: () => ({}) }), GleapNetworkIntercepter: manager({ getRequests: () => [{ url: 'https://app.example.com/api' }] }), @@ -34,11 +35,11 @@ jest.mock('./Gleap', () => { }; }); -jest.mock('./ScreenCapture', () => ({ - startScreenCapture: jest.fn(() => Promise.resolve({ html: '' })), +vi.mock('./ScreenCapture', () => ({ + startScreenCapture: vi.fn(() => Promise.resolve({ html: '' })), })); -jest.mock('./GleapScreenRecorder', () => ({ GleapScreenRecorder: { uploadFile: jest.fn() } })); +vi.mock('./GleapScreenRecorder', () => ({ GleapScreenRecorder: { uploadFile: vi.fn() } })); // Minimal XHR double: tests drive responses explicitly via respond(). class MockXhr { @@ -80,7 +81,7 @@ const send = async ({ isSilent = false, excludeData = {} } = {}) => { undefined, undefined ).sendFeedback(); - const settled = jest.fn(); + const settled = vi.fn(); result.then( (value) => settled('resolved', value), () => settled('rejected') diff --git a/src/GleapFrameManager.test.js b/src/GleapFrameManager.test.js index 3f907bb7..0a006b41 100644 --- a/src/GleapFrameManager.test.js +++ b/src/GleapFrameManager.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { loadFromGleapCache, saveToGleapCache } from './GleapHelper'; import GleapFrameManager, { FRAME_LOAD_TIMEOUT_MS } from './GleapFrameManager'; @@ -8,42 +9,45 @@ import GleapFrameManager, { FRAME_LOAD_TIMEOUT_MS } from './GleapFrameManager'; // Webpack global. flowConfig is a mutable object so tests can flip // hideExpandButton the way a config reload would. const mockFlowConfig = {}; -jest.mock('./Gleap', () => ({ +vi.mock('./Gleap', () => ({ __esModule: true, - default: { getInstance: jest.fn(() => ({ setGlobalDataItem: jest.fn() })) }, - GleapConfigManager: { getInstance: jest.fn(() => ({ getFlowConfig: () => mockFlowConfig })) }, + default: { getInstance: vi.fn(() => ({ setGlobalDataItem: vi.fn() })) }, + GleapConfigManager: { getInstance: vi.fn(() => ({ getFlowConfig: () => mockFlowConfig })) }, GleapFeedbackButtonManager: { - getInstance: jest.fn(() => ({ + getInstance: vi.fn(() => ({ buttonHidden: null, - updateNotificationBadge: jest.fn(), - updateFeedbackButtonState: jest.fn(), + updateNotificationBadge: vi.fn(), + updateFeedbackButtonState: vi.fn(), })), }, GleapTranslationManager: { - getInstance: jest.fn(() => ({ isRTLLayout: false, getOverrideLanguage: () => '' })), + getInstance: vi.fn(() => ({ isRTLLayout: false, getOverrideLanguage: () => '' })), }, GleapNotificationManager: { - getInstance: jest.fn(() => ({ clearAllNotifications: jest.fn(), reloadNotificationsFromCache: jest.fn() })), + getInstance: vi.fn(() => ({ clearAllNotifications: vi.fn(), reloadNotificationsFromCache: vi.fn() })), }, - GleapEventManager: { notifyEvent: jest.fn() }, - GleapBannerManager: { getInstance: jest.fn(() => ({})) }, - GleapSession: { getInstance: jest.fn(() => ({ getSession: () => ({}) })) }, + GleapEventManager: { notifyEvent: vi.fn() }, + GleapBannerManager: { getInstance: vi.fn(() => ({})) }, + GleapSession: { getInstance: vi.fn(() => ({ getSession: () => ({}) })) }, + // Not part of these tests: the frame manager skips capture messages without it. Vitest throws on an export a + // mock leaves out, so it is listed as absent. + GleapCaptureManager: undefined, })); -jest.mock('./GleapAgentToolManager', () => ({ +vi.mock('./GleapAgentToolManager', () => ({ __esModule: true, - default: { getInstance: jest.fn(() => ({ getAgentTools: () => [] })) }, + default: { getInstance: vi.fn(() => ({ getAgentTools: () => [] })) }, })); -jest.mock('./GleapHelper', () => ({ - loadFromGleapCache: jest.fn(() => null), - saveToGleapCache: jest.fn(), - bootstrapGleapFrame: jest.fn(), - runFunctionWhenDomIsReady: jest.fn(), +vi.mock('./GleapHelper', () => ({ + loadFromGleapCache: vi.fn(() => null), + saveToGleapCache: vi.fn(), + bootstrapGleapFrame: vi.fn(), + runFunctionWhenDomIsReady: vi.fn(), })); -jest.mock('./UI', () => ({ - widgetLoaderMarkup: jest.fn(() => ''), +vi.mock('./UI', () => ({ + widgetLoaderMarkup: vi.fn(() => ''), widgetMaxHeight: 700, widgetExpandMinWidth: 768, })); @@ -66,7 +70,7 @@ const setup = () => { previous = fm; fm.gleapFrameContainer = document.querySelector('.gleap-frame-container'); fm.comReady = true; - postMessage = jest.spyOn(document.querySelector('.gleap-frame').contentWindow, 'postMessage').mockImplementation(() => {}); + postMessage = vi.spyOn(document.querySelector('.gleap-frame').contentWindow, 'postMessage').mockImplementation(() => {}); return fm; }; @@ -88,7 +92,7 @@ const matchWidthQuery = (query) => { beforeEach(() => { isMobile = false; viewportWidth = 1440; - window.matchMedia = jest.fn(matchWidthQuery); + window.matchMedia = vi.fn(matchWidthQuery); Object.keys(mockFlowConfig).forEach((k) => delete mockFlowConfig[k]); loadFromGleapCache.mockReset().mockReturnValue(null); saveToGleapCache.mockReset(); @@ -276,7 +280,7 @@ describe('GleapFrameManager expand/collapse window', () => { describe('GleapFrameManager url handler', () => { let open; beforeEach(() => { - open = jest.spyOn(window, 'open').mockImplementation(() => null); + open = vi.spyOn(window, 'open').mockImplementation(() => null); }); afterEach(() => open.mockRestore()); @@ -299,7 +303,7 @@ describe('GleapFrameManager url handler', () => { it('runs a custom handler for deep links but never for script URLs', () => { const fm = setup(); - const custom = jest.fn(); + const custom = vi.fn(); fm.setUrlHandler(custom); fm.urlHandler('myapp://settings', false); fm.urlHandler('javascript:alert(1)', false); @@ -335,25 +339,25 @@ describe('GleapFrameManager opens reliably (iOS: never stuck until a reload)', ( }; beforeEach(() => { - jest.useFakeTimers(); - warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); + vi.useFakeTimers(); + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); }); afterEach(() => { - jest.useRealTimers(); + vi.useRealTimers(); warn.mockRestore(); }); it('keeps the loader up when opened again before the messenger pinged, and opens on the ping', () => { const fm = setupLoading(); fm.showWidget(); - jest.advanceTimersByTime(0); + vi.advanceTimersByTime(0); const container = fm.gleapFrameContainer; expect(container.classList.contains(HIDDEN)).toBe(false); expect(container.classList.contains(LOADING)).toBe(true); expect(fm.widgetOpened).toBe(true); dispatch(fm, { name: 'ping' }); - jest.advanceTimersByTime(300); + vi.advanceTimersByTime(300); expect(container.classList.contains(LOADING)).toBe(false); }); @@ -363,11 +367,11 @@ describe('GleapFrameManager opens reliably (iOS: never stuck until a reload)', ( fm.showFrameContainer(true); fm.armFrameLoadWatchdog(frame); - jest.advanceTimersByTime(FRAME_LOAD_TIMEOUT_MS); + vi.advanceTimersByTime(FRAME_LOAD_TIMEOUT_MS); expect(frame.getAttribute('src')).toBe(fm.frameUrl); expect(fm.gleapFrameContainer).not.toBeNull(); - jest.advanceTimersByTime(FRAME_LOAD_TIMEOUT_MS); + vi.advanceTimersByTime(FRAME_LOAD_TIMEOUT_MS); expect(fm.gleapFrameContainer).toBeNull(); expect(fm.injectedFrame).toBe(false); expect(fm.widgetOpened).toBe(false); @@ -379,7 +383,7 @@ describe('GleapFrameManager opens reliably (iOS: never stuck until a reload)', ( const fm = setupLoading(); fm.armFrameLoadWatchdog(fm.gleapFrame); dispatch(fm, { name: 'ping' }); - jest.advanceTimersByTime(FRAME_LOAD_TIMEOUT_MS * 2); + vi.advanceTimersByTime(FRAME_LOAD_TIMEOUT_MS * 2); expect(fm.gleapFrame.getAttribute('src')).toBeNull(); expect(fm.gleapFrameContainer).not.toBeNull(); }); @@ -397,14 +401,14 @@ describe('GleapFrameManager opens reliably (iOS: never stuck until a reload)', ( it('restarts a frame that was still loading when the page went into the back/forward cache', () => { const fm = setupLoading(); fm.showFrameContainer(true); - const inject = jest.spyOn(fm, 'injectFrame').mockImplementation(() => {}); - const instance = jest.spyOn(GleapFrameManager, 'getInstance').mockReturnValue(fm); + const inject = vi.spyOn(fm, 'injectFrame').mockImplementation(() => {}); + const instance = vi.spyOn(GleapFrameManager, 'getInstance').mockReturnValue(fm); fm.handlePageShow({ persisted: true }); expect(document.querySelector('.gleap-frame-container')).toBeNull(); expect(fm.injectedFrame).toBe(false); - jest.advanceTimersByTime(0); + vi.advanceTimersByTime(0); expect(inject).toHaveBeenCalledTimes(1); instance.mockRestore(); }); diff --git a/src/GleapHelper.bootstrap.file.test.js b/src/GleapHelper.bootstrap.file.test.js index f4026a00..472f9462 100644 --- a/src/GleapHelper.bootstrap.file.test.js +++ b/src/GleapHelper.bootstrap.file.test.js @@ -1,7 +1,8 @@ /** - * @jest-environment jsdom - * @jest-environment-options {"url": "file:///C:/Users/me/AppData/Local/Programs/twinmind/resources/app.asar/dist/renderer/index.html"} + * @vitest-environment jsdom + * @vitest-environment-options {"url": "file:///C:/Users/me/AppData/Local/Programs/twinmind/resources/app.asar/dist/renderer/index.html"} */ +import { describe, it, expect, vi, afterEach } from 'vitest'; import { bootstrapGleapFrame, isHttpDocument } from './GleapHelper'; const MODAL_URL = 'https://outboundmedia.gleap.io/modal'; @@ -19,7 +20,7 @@ describe('bootstrapGleapFrame inside a file:// host document', () => { }); it('skips the about:blank bootstrap and loads the frame directly', async () => { - global.fetch = jest.fn(); + global.fetch = vi.fn(); const iframe = document.createElement('iframe'); document.body.appendChild(iframe); diff --git a/src/GleapHelper.bootstrap.test.js b/src/GleapHelper.bootstrap.test.js index f2760522..3aceac85 100644 --- a/src/GleapHelper.bootstrap.test.js +++ b/src/GleapHelper.bootstrap.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { bootstrapGleapFrame, warnOnCSPViolation, isHttpDocument, ROUTE_FAILED_EVENT } from './GleapHelper'; const MODAL_URL = 'https://outboundmedia.gleap.io/modal'; @@ -20,18 +21,18 @@ let warn; beforeEach(() => { document.body.innerHTML = ''; - warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); }); afterEach(() => { - jest.restoreAllMocks(); + vi.restoreAllMocks(); delete global.fetch; }); describe('bootstrapGleapFrame on a regular http(s) page', () => { it('fetches the app document from the Gleap origin', async () => { expect(isHttpDocument()).toBe(true); - global.fetch = jest.fn(() => okResponse('')); + global.fetch = vi.fn(() => okResponse('')); const iframe = appendFrame(); bootstrapGleapFrame(iframe, MODAL_URL); @@ -41,7 +42,7 @@ describe('bootstrapGleapFrame on a regular http(s) page', () => { }); it('keeps the bootstrapped document when the app route was applied', async () => { - global.fetch = jest.fn(() => okResponse('')); + global.fetch = vi.fn(() => okResponse('')); const iframe = appendFrame(); // Give the frame a same-origin http document URL, as browsers do after doc.open() (jsdom // keeps about:blank, against which no path can be set — see the next test). @@ -59,9 +60,9 @@ describe('bootstrapGleapFrame on a regular http(s) page', () => { // replaceState is refused on some origins (sandboxed, file://, exotic schemes — and jsdom's // about:blank). The route script swallows that, and the app router would then match // nothing: a blank frame. - global.fetch = jest.fn(() => okResponse('')); + global.fetch = vi.fn(() => okResponse('')); const iframe = appendFrame(); - const listener = jest.fn(); + const listener = vi.fn(); iframe.addEventListener(ROUTE_FAILED_EVENT, listener); bootstrapGleapFrame(iframe, MODAL_URL); @@ -72,7 +73,7 @@ describe('bootstrapGleapFrame on a regular http(s) page', () => { }); it('loads the frame directly when the fetch fails', async () => { - global.fetch = jest.fn(() => Promise.reject(new TypeError('Failed to fetch'))); + global.fetch = vi.fn(() => Promise.reject(new TypeError('Failed to fetch'))); const iframe = appendFrame(); bootstrapGleapFrame(iframe, MODAL_URL); @@ -83,8 +84,8 @@ describe('bootstrapGleapFrame on a regular http(s) page', () => { }); it('never assigns src twice, however many checks conclude the same thing', async () => { - global.fetch = jest.fn(() => okResponse('')); - const setSrc = jest.spyOn(HTMLIFrameElement.prototype, 'src', 'set'); + global.fetch = vi.fn(() => okResponse('')); + const setSrc = vi.spyOn(HTMLIFrameElement.prototype, 'src', 'set'); const iframe = appendFrame(); // Route failure (about:blank, see above) and a CSP block on the bundle, back to back. bootstrapGleapFrame(iframe, MODAL_URL); @@ -109,7 +110,7 @@ describe('warnOnCSPViolation fallback hook', () => { beforeEach(() => { doc = document.implementation.createHTMLDocument('frame'); - onBlocked = jest.fn(); + onBlocked = vi.fn(); warnOnCSPViolation(doc, { baseHref: BASE_HREF, onBlocked }); }); diff --git a/src/GleapHelper.test.js b/src/GleapHelper.test.js index e7d78c4c..4d0c82ad 100644 --- a/src/GleapHelper.test.js +++ b/src/GleapHelper.test.js @@ -1,3 +1,4 @@ +import { describe, test, expect } from 'vitest'; import { cookieDomainFor, eraseGleapCookie, flattenCompany, formatRelativeTime, setGleapCookie } from './GleapHelper'; describe('formatRelativeTime — the notification meta line', () => { @@ -339,7 +340,7 @@ describe('cookie domain', () => { ['[2001:db8::7]:443', null], ['::1', null], ['', null], - ])('cookieDomainFor(%p) is %p', (host, domain) => { + ])('cookieDomainFor(%j) is %j', (host, domain) => { expect(cookieDomainFor(host)).toBe(domain); }); diff --git a/src/GleapHighlight.test.js b/src/GleapHighlight.test.js index bc47550d..7d08b44a 100644 --- a/src/GleapHighlight.test.js +++ b/src/GleapHighlight.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, expect, vi, beforeEach, afterEach, beforeAll } from 'vitest'; import { checkForHighlightParam, clearHighlight, @@ -35,7 +36,7 @@ describe('GleapHighlight', () => { afterEach(() => { clearHighlight(); - jest.useRealTimers(); + vi.useRealTimers(); }); describe('scoreLabel', () => { @@ -95,7 +96,7 @@ describe('GleapHighlight', () => { describe('showHighlight', () => { beforeAll(() => { - Element.prototype.scrollIntoView = jest.fn(); + Element.prototype.scrollIntoView = vi.fn(); }); it('outlines the element and removes the outline on the next click', () => { @@ -110,16 +111,16 @@ describe('GleapHighlight', () => { }); it('fades out on its own', () => { - jest.useFakeTimers(); + vi.useFakeTimers(); showHighlight(document.getElementById('save')); - jest.advanceTimersByTime(7000); + vi.advanceTimersByTime(7000); expect(document.getElementById('gleap-highlight-overlay')).toBeNull(); }); }); describe('checkForHighlightParam', () => { it('strips the parameter, keeps the rest of the URL and the router state, and waits for the element', () => { - jest.useFakeTimers(); + vi.useFakeTimers(); document.body.innerHTML = '
'; window.history.replaceState({ route: 'settings' }, '', '/account/settings/publishing?tab=1&gleap_highlight=Post+as+draft#top'); @@ -135,7 +136,7 @@ describe('GleapHighlight', () => { const original = Element.prototype.getClientRects; Element.prototype.getClientRects = () => [{}]; try { - jest.advanceTimersByTime(400); + vi.advanceTimersByTime(400); expect(document.getElementById('gleap-highlight-overlay')).not.toBeNull(); } finally { Element.prototype.getClientRects = original; diff --git a/src/GleapInitialize.test.js b/src/GleapInitialize.test.js index 92c5b85c..b77c0dfa 100644 --- a/src/GleapInitialize.test.js +++ b/src/GleapInitialize.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest'; import Gleap, { GleapSession } from './Gleap'; // initialize() names the key "Project ID"; the positional form keeps working. @@ -12,8 +13,8 @@ describe('Gleap.initialize(projectId)', () => { Gleap.getInstance().initialized = false; GleapSession.instance = undefined; // startSession is an instance arrow property: stub it on the fresh singleton. - startSpy = jest.spyOn(GleapSession.getInstance(), 'startSession').mockImplementation(() => {}); - warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {}); + startSpy = vi.spyOn(GleapSession.getInstance(), 'startSession').mockImplementation(() => {}); + warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); }); afterEach(() => { diff --git a/src/GleapInputFiller.test.js b/src/GleapInputFiller.test.js index defb493c..74f9437e 100644 --- a/src/GleapInputFiller.test.js +++ b/src/GleapInputFiller.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { resolveInputTarget, setInputValue, typeIntoElement } from './GleapInputFiller'; const realInputValue = (element) => @@ -111,11 +112,11 @@ describe('setInputValue', () => { describe('typeIntoElement', () => { beforeEach(() => { - jest.useFakeTimers(); + vi.useFakeTimers(); document.body.innerHTML = ''; }); afterEach(() => { - jest.useRealTimers(); + vi.useRealTimers(); }); it('types the exact value and fires one input event per character plus a final change', () => { @@ -125,10 +126,10 @@ describe('typeIntoElement', () => { const changeEvents = []; input.addEventListener('input', (e) => inputEvents.push(e.target.value)); input.addEventListener('change', (e) => changeEvents.push(e.target.value)); - const onDone = jest.fn(); + const onDone = vi.fn(); typeIntoElement(input, 'Oslo', { charDelay: 100, onDone }); - jest.advanceTimersByTime(1000); + vi.advanceTimersByTime(1000); expect(input.value).toBe('Oslo'); expect(inputEvents).toEqual(['O', 'Os', 'Osl', 'Oslo']); @@ -142,7 +143,7 @@ describe('typeIntoElement', () => { document.body.appendChild(input); typeIntoElement(input, 'new', { charDelay: 100 }); - jest.advanceTimersByTime(1000); + vi.advanceTimersByTime(1000); expect(input.value).toBe('new'); }); @@ -154,7 +155,7 @@ describe('typeIntoElement', () => { document.body.appendChild(field); typeIntoElement(field, 'Oslo', { charDelay: 100 }); - jest.advanceTimersByTime(1000); + vi.advanceTimersByTime(1000); expect(field.querySelector('input').value).toBe('Oslo'); }); @@ -162,10 +163,10 @@ describe('typeIntoElement', () => { it('still calls onDone when there is nothing to type into, so the tour never stalls', () => { const div = document.createElement('div'); document.body.appendChild(div); - const onDone = jest.fn(); + const onDone = vi.fn(); typeIntoElement(div, 'Oslo', { charDelay: 100, onDone }); - jest.advanceTimersByTime(1000); + vi.advanceTimersByTime(1000); expect(onDone).toHaveBeenCalledTimes(1); }); @@ -181,11 +182,11 @@ describe('typeIntoElement', () => { get: () => '', configurable: true, }); - const onDone = jest.fn(); + const onDone = vi.fn(); expect(() => { typeIntoElement(editable, 'Oslo', { charDelay: 100, onDone }); - jest.advanceTimersByTime(1000); + vi.advanceTimersByTime(1000); }).not.toThrow(); expect(onDone).toHaveBeenCalledTimes(1); }); @@ -193,10 +194,10 @@ describe('typeIntoElement', () => { it('handles an empty value without hanging', () => { const input = document.createElement('input'); document.body.appendChild(input); - const onDone = jest.fn(); + const onDone = vi.fn(); typeIntoElement(input, '', { charDelay: 100, onDone }); - jest.advanceTimersByTime(1000); + vi.advanceTimersByTime(1000); expect(input.value).toBe(''); expect(onDone).toHaveBeenCalledTimes(1); diff --git a/src/GleapInputMasking.test.js b/src/GleapInputMasking.test.js index 1159c8b2..be90b39c 100644 --- a/src/GleapInputMasking.test.js +++ b/src/GleapInputMasking.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, test, expect } from 'vitest'; import GleapReplayRecorder from './GleapReplayRecorder'; import { startScreenCapture } from './ScreenCapture'; diff --git a/src/GleapMarkerManager.test.js b/src/GleapMarkerManager.test.js index 0db57d50..9dc2485b 100644 --- a/src/GleapMarkerManager.test.js +++ b/src/GleapMarkerManager.test.js @@ -1,15 +1,16 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { test, expect, vi, beforeEach } from 'vitest'; import GleapMarkerManager from './GleapMarkerManager'; import { captureTabScreenshot, requestTabStream } from './GleapCaptureScreenshot'; import { canCaptureTab } from './GleapCaptureSettings'; // The feedback form's "Mark the bug" step takes its screenshot from the tab on Next (#228450). const mockGlobalData = {}; -const mockSendMessage = jest.fn(); +const mockSendMessage = vi.fn(); -jest.mock('./Gleap', () => ({ +vi.mock('./Gleap', () => ({ __esModule: true, default: { getInstance: () => ({ @@ -25,12 +26,12 @@ jest.mock('./Gleap', () => ({ getInstance: () => ({ privacyOptions: () => ({ maskAllInputs: true }), maskSelectors: () => ['.secret'] }), }, })); -jest.mock('./ScreenDrawer', () => ({ ScreenDrawer: jest.fn() })); -jest.mock('./GleapScrollStopper', () => ({ GleapScrollStopper: { enableScroll: jest.fn(), disableScroll: jest.fn() } })); -jest.mock('./GleapScreenRecorder', () => ({ GleapScreenRecorder: jest.fn() })); -jest.mock('./UI', () => ({ loadIcon: () => '' })); -jest.mock('./GleapCaptureSettings', () => ({ canCaptureTab: jest.fn() })); -jest.mock('./GleapCaptureScreenshot', () => ({ captureTabScreenshot: jest.fn(), requestTabStream: jest.fn() })); +vi.mock('./ScreenDrawer', () => ({ ScreenDrawer: vi.fn() })); +vi.mock('./GleapScrollStopper', () => ({ GleapScrollStopper: { enableScroll: vi.fn(), disableScroll: vi.fn() } })); +vi.mock('./GleapScreenRecorder', () => ({ GleapScreenRecorder: vi.fn() })); +vi.mock('./UI', () => ({ loadIcon: () => '' })); +vi.mock('./GleapCaptureSettings', () => ({ canCaptureTab: vi.fn() })); +vi.mock('./GleapCaptureScreenshot', () => ({ captureTabScreenshot: vi.fn(), requestTabStream: vi.fn() })); const IMAGE = { dataUrl: 'data:image/jpeg;base64,/9j/4AAQ', width: 1280, height: 720, method: 'tab' }; const STREAM_PROMISE = Promise.resolve({ id: 'tab-stream' }); @@ -55,7 +56,7 @@ beforeEach(() => { document.body.innerHTML = ''; manager = new GleapMarkerManager('screenshot'); manager.createEditorUI(); - callback = jest.fn(); + callback = vi.fn(); manager.callback = callback; }); diff --git a/src/GleapMessageSecurity.test.js b/src/GleapMessageSecurity.test.js index 04d90e05..aff98d63 100644 --- a/src/GleapMessageSecurity.test.js +++ b/src/GleapMessageSecurity.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, test, expect } from 'vitest'; import { frameTargetOrigin, isSafeNavigationUrl, isScriptUrl, originMatchesUrl } from './GleapMessageSecurity'; describe('isSafeNavigationUrl (default url handler)', () => { @@ -25,7 +26,7 @@ describe('isSafeNavigationUrl (default url handler)', () => { undefined, null, {}, - ])('rejects %p', (url) => { + ])('rejects %j', (url) => { expect(isSafeNavigationUrl(url)).toBe(false); }); }); diff --git a/src/GleapMetaDataManager.test.js b/src/GleapMetaDataManager.test.js index c83eb107..e0fc4afa 100644 --- a/src/GleapMetaDataManager.test.js +++ b/src/GleapMetaDataManager.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, test, expect, vi, beforeEach } from 'vitest'; import GleapMetaDataManager from './GleapMetaDataManager'; // Normally injected by Webpack's DefinePlugin. @@ -49,7 +50,7 @@ describe('GleapMetaDataManager env data controls', () => { test('disabled env data is not gathered at all', () => { const instance = GleapMetaDataManager.getInstance(); - const collect = jest.spyOn(instance, 'collectMetaData'); + const collect = vi.spyOn(instance, 'collectMetaData'); GleapMetaDataManager.setDisableEnvData(true); diff --git a/src/GleapModalManager.test.js b/src/GleapModalManager.test.js index 0f386b2e..e353837d 100644 --- a/src/GleapModalManager.test.js +++ b/src/GleapModalManager.test.js @@ -1,21 +1,22 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import GleapModalManager from './GleapModalManager'; // Stub the barrel so the real GleapModalManager loads without the rest of the SDK. // We only drive the modal-height contract, which reaches GleapConfigManager. -jest.mock('./Gleap', () => ({ +vi.mock('./Gleap', () => ({ __esModule: true, default: {}, GleapConfigManager: { - getInstance: jest.fn(() => ({ getFlowConfig: () => ({}) })), + getInstance: vi.fn(() => ({ getFlowConfig: () => ({}) })), }, - GleapFrameManager: { getInstance: jest.fn(() => ({ urlHandler: jest.fn() })) }, + GleapFrameManager: { getInstance: vi.fn(() => ({ urlHandler: vi.fn() })) }, })); -jest.mock('./GleapHelper', () => ({ - bootstrapGleapFrame: jest.fn(), +vi.mock('./GleapHelper', () => ({ + bootstrapGleapFrame: vi.fn(), })); const MODAL_ORIGIN = 'https://outboundmedia.gleap.io'; @@ -43,13 +44,13 @@ beforeEach(() => { document.body.className = ''; setViewportHeight(800); manager = new GleapModalManager(); - jest.spyOn(manager, '_postMessage').mockImplementation(() => {}); + vi.spyOn(manager, '_postMessage').mockImplementation(() => {}); manager.showModal({ config: { steps: [{ title: 'Hi' }] } }); }); afterEach(() => { manager.hideModal(); - jest.restoreAllMocks(); + vi.restoreAllMocks(); }); const postedMessages = (name) => manager._postMessage.mock.calls.map((c) => c[0]).filter((m) => m.name === name); diff --git a/src/GleapModalManager.watchdog.test.js b/src/GleapModalManager.watchdog.test.js index e4b50eca..df16105a 100644 --- a/src/GleapModalManager.watchdog.test.js +++ b/src/GleapModalManager.watchdog.test.js @@ -1,20 +1,21 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import GleapModalManager, { MODAL_LOAD_TIMEOUT_MS } from './GleapModalManager'; import { bootstrapGleapFrame } from './GleapHelper'; -jest.mock('./Gleap', () => ({ +vi.mock('./Gleap', () => ({ __esModule: true, default: {}, GleapConfigManager: { - getInstance: jest.fn(() => ({ getFlowConfig: () => ({}) })), + getInstance: vi.fn(() => ({ getFlowConfig: () => ({}) })), }, - GleapFrameManager: { getInstance: jest.fn(() => ({ urlHandler: jest.fn() })) }, + GleapFrameManager: { getInstance: vi.fn(() => ({ urlHandler: vi.fn() })) }, })); -jest.mock('./GleapHelper', () => ({ - bootstrapGleapFrame: jest.fn(), +vi.mock('./GleapHelper', () => ({ + bootstrapGleapFrame: vi.fn(), })); const MODAL_URL = 'https://outboundmedia.gleap.io/modal'; @@ -36,19 +37,19 @@ let manager; let warn; beforeEach(() => { - jest.useFakeTimers(); + vi.useFakeTimers(); document.body.innerHTML = ''; document.body.className = ''; bootstrapGleapFrame.mockReset(); - warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); manager = new GleapModalManager(); - jest.spyOn(manager, '_postMessage').mockImplementation(() => {}); + vi.spyOn(manager, '_postMessage').mockImplementation(() => {}); }); afterEach(() => { manager.hideModal(); - jest.restoreAllMocks(); - jest.useRealTimers(); + vi.restoreAllMocks(); + vi.useRealTimers(); }); describe('the card stays invisible until it has content', () => { @@ -73,10 +74,10 @@ describe('load watchdog', () => { expect(bootstrapGleapFrame).toHaveBeenCalledWith(frame(), MODAL_URL); expect(frame().getAttribute('src')).toBeNull(); - jest.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS - 1); + vi.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS - 1); expect(frame().getAttribute('src')).toBeNull(); - jest.advanceTimersByTime(1); + vi.advanceTimersByTime(1); expect(frame().getAttribute('src')).toBe(MODAL_URL); // Still showing — the direct load gets its own chance. expect(wrapper()).not.toBeNull(); @@ -86,7 +87,7 @@ describe('load watchdog', () => { it('takes the blank card down when the direct load does not report in either', () => { manager.showModal({ config: { steps: [{ title: 'Hi' }] } }); - jest.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS * 2); + vi.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS * 2); expect(wrapper()).toBeNull(); expect(document.body.classList.contains('gleap-modal-open')).toBe(false); @@ -98,7 +99,7 @@ describe('load watchdog', () => { manager.showModal({ config: { steps: [{ title: 'Hi' }] } }); emitFromModal('modal-loaded'); - jest.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS * 3); + vi.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS * 3); expect(frame().getAttribute('src')).toBeNull(); expect(wrapper()).not.toBeNull(); @@ -108,12 +109,12 @@ describe('load watchdog', () => { it('accepts a late modal-loaded from the direct load and keeps the card', () => { manager.showModal({ config: { steps: [{ title: 'Hi' }] } }); - jest.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS); + vi.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS); expect(frame().getAttribute('src')).toBe(MODAL_URL); emitFromModal('modal-loaded'); emitFromModal('modal-height', { height: 200 }); - jest.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS * 2); + vi.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS * 2); expect(wrapper()).not.toBeNull(); expect(wrapper().classList.contains('gleap-modal-wrapper--loading')).toBe(false); @@ -124,15 +125,15 @@ describe('load watchdog', () => { bootstrapGleapFrame.mockImplementation((iframe, url) => { iframe.src = url; }); - const setSrc = jest.spyOn(HTMLIFrameElement.prototype, 'src', 'set'); + const setSrc = vi.spyOn(HTMLIFrameElement.prototype, 'src', 'set'); manager.showModal({ config: { steps: [{ title: 'Hi' }] } }); expect(setSrc).toHaveBeenCalledTimes(1); - jest.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS); + vi.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS); expect(setSrc).toHaveBeenCalledTimes(1); // ...but it still gives up on it eventually. - jest.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS); + vi.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS); expect(wrapper()).toBeNull(); }); @@ -140,21 +141,21 @@ describe('load watchdog', () => { manager.showModal({ config: { steps: [{ title: 'Hi' }] } }); manager.hideModal(); - jest.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS * 3); + vi.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS * 3); expect(warn).not.toHaveBeenCalled(); expect(manager.modalLoadTimeout).toBeNull(); }); it('re-arms for every show, even while a previous card is still pending', () => { manager.showModal({ config: { steps: [{ title: 'first' }] } }); - jest.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS - 100); + vi.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS - 100); manager.showModal({ config: { steps: [{ title: 'second' }] } }); - jest.advanceTimersByTime(200); + vi.advanceTimersByTime(200); // The first card's timer must not have fired against the second card. expect(frame().getAttribute('src')).toBeNull(); - jest.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS - 200); + vi.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS - 200); expect(frame().getAttribute('src')).toBe(MODAL_URL); }); }); diff --git a/src/GleapNetworkLogSanitizer.test.js b/src/GleapNetworkLogSanitizer.test.js index 83bae5a1..0252ee0a 100644 --- a/src/GleapNetworkLogSanitizer.test.js +++ b/src/GleapNetworkLogSanitizer.test.js @@ -1,3 +1,4 @@ +import { describe, test, expect } from 'vitest'; import { REDACTED_VALUE, sanitizeNetworkLogs } from './GleapNetworkLogSanitizer'; import GleapNetworkIntercepter from './GleapNetworkIntercepter'; diff --git a/src/GleapNotificationManager.test.js b/src/GleapNotificationManager.test.js index d55aca13..38ef1898 100644 --- a/src/GleapNotificationManager.test.js +++ b/src/GleapNotificationManager.test.js @@ -1,3 +1,4 @@ +import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest'; import Gleap, { GleapTabCommunication, GleapSession, GleapAudioManager } from './Gleap'; import { loadFromGleapCache, saveToGleapCache } from './GleapHelper'; import GleapNotificationManager from './GleapNotificationManager'; @@ -5,30 +6,30 @@ import GleapNotificationManager from './GleapNotificationManager'; // Stub the barrel so the real GleapNotificationManager loads without a DOM or the // SDK_VERSION Webpack global. We only drive clearAllNotifications, which reaches // GleapTabCommunication, GleapSession and saveToGleapCache. -jest.mock('./Gleap', () => ({ +vi.mock('./Gleap', () => ({ __esModule: true, - default: { getInstance: jest.fn() }, - GleapFeedbackButtonManager: { getInstance: jest.fn(() => ({ updateNotificationBadge: jest.fn() })) }, - GleapConfigManager: { getInstance: jest.fn(() => ({ getFlowConfig: () => ({}) })) }, - GleapSession: { getInstance: jest.fn() }, - GleapAudioManager: { ping: jest.fn() }, + default: { getInstance: vi.fn() }, + GleapFeedbackButtonManager: { getInstance: vi.fn(() => ({ updateNotificationBadge: vi.fn() })) }, + GleapConfigManager: { getInstance: vi.fn(() => ({ getFlowConfig: () => ({}) })) }, + GleapSession: { getInstance: vi.fn() }, + GleapAudioManager: { ping: vi.fn() }, GleapTranslationManager: { - getInstance: jest.fn(() => ({ isRTLLayout: false, getActiveLanguage: () => 'en' })), + getInstance: vi.fn(() => ({ isRTLLayout: false, getActiveLanguage: () => 'en' })), translateText: (s) => s, }, - GleapEventManager: { notifyEvent: jest.fn() }, - GleapAiChatbarManager: { getInstance: jest.fn(() => ({})) }, - GleapTabCommunication: { getInstance: jest.fn() }, + GleapEventManager: { notifyEvent: vi.fn() }, + GleapAiChatbarManager: { getInstance: vi.fn(() => ({})) }, + GleapTabCommunication: { getInstance: vi.fn() }, })); -jest.mock('./GleapHelper', () => ({ - loadFromGleapCache: jest.fn(), - saveToGleapCache: jest.fn(), - formatRelativeTime: jest.fn(() => 'now'), +vi.mock('./GleapHelper', () => ({ + loadFromGleapCache: vi.fn(), + saveToGleapCache: vi.fn(), + formatRelativeTime: vi.fn(() => 'now'), })); -jest.mock('./UI', () => ({ - loadIcon: jest.fn(() => ''), +vi.mock('./UI', () => ({ + loadIcon: vi.fn(() => ''), })); let sendMessageMock; @@ -36,16 +37,16 @@ let sendMessageMock; const withContainer = (nm) => { nm.notificationContainer = { firstChild: null, - appendChild: jest.fn(), - removeChild: jest.fn(), - classList: { add: jest.fn(), remove: jest.fn(), toggle: jest.fn(), contains: jest.fn(() => false) }, + appendChild: vi.fn(), + removeChild: vi.fn(), + classList: { add: vi.fn(), remove: vi.fn(), toggle: vi.fn(), contains: vi.fn(() => false) }, }; return nm; }; beforeEach(() => { Gleap.getInstance.mockReturnValue({ disableInAppNotifications: false }); - sendMessageMock = jest.fn(); + sendMessageMock = vi.fn(); GleapTabCommunication.getInstance.mockReturnValue({ sendMessage: sendMessageMock }); GleapSession.getInstance.mockReturnValue({ session: { gleapId: 'user-1' } }); @@ -78,7 +79,7 @@ describe('clearNotificationsForConversation', () => { test('filters in-memory notifications and re-renders when something was removed', () => { const nm = GleapNotificationManager.getInstance(); - const renderSpy = jest.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); + const renderSpy = vi.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); const keep = convNotification('token-other'); nm.notifications = [convNotification('token-read'), keep]; loadFromGleapCache.mockReturnValue(null); @@ -91,7 +92,7 @@ describe('clearNotificationsForConversation', () => { test('does not re-render when nothing matched', () => { const nm = GleapNotificationManager.getInstance(); - const renderSpy = jest.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); + const renderSpy = vi.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); nm.notifications = [convNotification('token-other')]; loadFromGleapCache.mockReturnValue(null); @@ -170,7 +171,7 @@ describe('page rules — render-time evaluation (#141052)', () => { saveToGleapCache.mockReset(); // The suite runs in the node environment; renderNotifications only needs // createElement + property assignments, so a minimal stub is enough. - global.document = { createElement: jest.fn(() => ({})) }; + global.document = { createElement: vi.fn(() => ({})) }; setUrl(ALLOWED_URL); }); @@ -221,7 +222,7 @@ describe('page rules — render-time evaluation (#141052)', () => { test('checkPageRulesForUrl re-renders only once per URL', () => { const nm = GleapNotificationManager.getInstance(); - const renderSpy = jest.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); + const renderSpy = vi.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); nm.notifications = [pageRuledNotification()]; nm.checkPageRulesForUrl(ALLOWED_URL); @@ -232,7 +233,7 @@ describe('page rules — render-time evaluation (#141052)', () => { test('checkPageRulesForUrl skips re-rendering when nothing is page-ruled', () => { const nm = GleapNotificationManager.getInstance(); - const renderSpy = jest.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); + const renderSpy = vi.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); nm.notifications = [plainNotification()]; nm.checkPageRulesForUrl('https://a.example.com/1'); @@ -243,7 +244,7 @@ describe('page rules — render-time evaluation (#141052)', () => { test('legacy single pageFilter notifications also trigger re-evaluation', () => { const nm = GleapNotificationManager.getInstance(); - const renderSpy = jest.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); + const renderSpy = vi.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); nm.notifications = [{ outbound: 'o1', data: { text: 'x' }, pageFilter: '/x', pageFilterType: 'notcontains' }]; nm.checkPageRulesForUrl('https://a.example.com/1'); @@ -266,7 +267,7 @@ describe('page rules — render-time evaluation (#141052)', () => { test('a notification arriving on an excluded page is stored + persisted (not consumed), without a ping', () => { setUrl(EXCLUDED_URL); const nm = withContainer(GleapNotificationManager.getInstance()); - jest.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); + vi.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); const notification = { ...pageRuledNotification(), sound: true }; nm.showNotification(notification); @@ -278,7 +279,7 @@ describe('page rules — render-time evaluation (#141052)', () => { test('a notification arriving on an allowed page still pings', () => { const nm = withContainer(GleapNotificationManager.getInstance()); - jest.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); + vi.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); nm.showNotification({ ...pageRuledNotification(), sound: true }); @@ -298,7 +299,7 @@ describe('notification stack', () => { loadFromGleapCache.mockReset(); saveToGleapCache.mockReset(); global.window = { location: { href: 'https://a.example.com/' } }; - global.document = { createElement: jest.fn(() => ({})) }; + global.document = { createElement: vi.fn(() => ({})) }; }); afterEach(() => { @@ -308,7 +309,7 @@ describe('notification stack', () => { test('showNotification keeps the newest 4, dropping the oldest beyond that', () => { const nm = withContainer(GleapNotificationManager.getInstance()); - jest.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); + vi.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); for (let i = 1; i <= 6; i++) { nm.showNotification(plainNotification(`n${i}`)); @@ -319,7 +320,7 @@ describe('notification stack', () => { test('reloadNotificationsFromCache keeps the NEWEST 4 (the same end shift() trims from)', () => { const nm = withContainer(GleapNotificationManager.getInstance()); - jest.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); + vi.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); loadFromGleapCache.mockReturnValue( [1, 2, 3, 4, 5, 6].map((i) => ({ ...plainNotification(`n${i}`), cachedForGleapId: 'user-1' })) ); @@ -412,7 +413,7 @@ describe('notification cache vs identity (#225880)', () => { test('showNotification stamps the receiving gleapId on the cached notification', () => { const nm = withContainer(GleapNotificationManager.getInstance()); - jest.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); + vi.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); nm.showNotification(plainNotification('hello')); @@ -423,7 +424,7 @@ describe('notification cache vs identity (#225880)', () => { test('reloadNotificationsFromCache drops notifications cached for another (or no) gleapId', () => { const nm = withContainer(GleapNotificationManager.getInstance()); - jest.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); + vi.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); const own = plainNotification('own', 'user-1'); loadFromGleapCache.mockReturnValue([ plainNotification('previous user', 'user-0'), diff --git a/src/GleapNotifications.disabled.test.js b/src/GleapNotifications.disabled.test.js index 26e21f1b..c56fa5e2 100644 --- a/src/GleapNotifications.disabled.test.js +++ b/src/GleapNotifications.disabled.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { test, expect, vi, beforeEach, afterEach } from 'vitest'; import Gleap, { GleapAudioManager, GleapConfigManager, @@ -30,20 +31,20 @@ const visibleCards = (manager) => manager.notificationContainer.querySelectorAll beforeEach(() => { // Exercise the real public setter and notification renderer, without SDK startup. - jest.spyOn(Gleap, 'getInstance').mockReturnValue({ disableInAppNotifications: false }); - jest.spyOn(GleapSession, 'getInstance').mockReturnValue({ + vi.spyOn(Gleap, 'getInstance').mockReturnValue({ disableInAppNotifications: false }); + vi.spyOn(GleapSession, 'getInstance').mockReturnValue({ session: { gleapId: 'signup-visitor' }, getName: () => 'Visitor', }); - jest.spyOn(GleapConfigManager, 'getInstance').mockReturnValue({ getFlowConfig: () => ({}) }); - jest.spyOn(GleapAudioManager, 'ping').mockImplementation(() => {}); - jest.spyOn(cache, 'loadFromGleapCache').mockReturnValue(null); - jest.spyOn(cache, 'saveToGleapCache').mockImplementation(() => {}); + vi.spyOn(GleapConfigManager, 'getInstance').mockReturnValue({ getFlowConfig: () => ({}) }); + vi.spyOn(GleapAudioManager, 'ping').mockImplementation(() => {}); + vi.spyOn(cache, 'loadFromGleapCache').mockReturnValue(null); + vi.spyOn(cache, 'saveToGleapCache').mockImplementation(() => {}); GleapNotificationManager.instance = undefined; }); afterEach(() => { - jest.restoreAllMocks(); + vi.restoreAllMocks(); GleapNotificationManager.instance = undefined; document.body.innerHTML = ''; }); @@ -111,9 +112,9 @@ test('reenabling notifications still respects their page exclusions', () => { }); test('support chat can still open while notification cards are disabled', () => { - const frame = { setAppMode: jest.fn(), showWidget: jest.fn(), hideWidget: jest.fn() }; - jest.spyOn(GleapFrameManager, 'getInstance').mockReturnValue(frame); - const buttonManager = jest.spyOn(GleapFeedbackButtonManager, 'getInstance'); + const frame = { setAppMode: vi.fn(), showWidget: vi.fn(), hideWidget: vi.fn() }; + vi.spyOn(GleapFrameManager, 'getInstance').mockReturnValue(frame); + const buttonManager = vi.spyOn(GleapFeedbackButtonManager, 'getInstance'); Gleap.setDisableInAppNotifications(true); Gleap.open(); diff --git a/src/GleapPageFilter.test.js b/src/GleapPageFilter.test.js index 342abeee..81ee7515 100644 --- a/src/GleapPageFilter.test.js +++ b/src/GleapPageFilter.test.js @@ -1,3 +1,4 @@ +import { describe, it, test, expect } from 'vitest'; import { checkPageRules, checkPageFilter } from './GleapPageFilter'; const url = (path) => `https://app.example.com${path}`; diff --git a/src/GleapProductTourStart.test.js b/src/GleapProductTourStart.test.js index a2825ba2..715c1412 100644 --- a/src/GleapProductTourStart.test.js +++ b/src/GleapProductTourStart.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, expect, vi, afterEach } from 'vitest'; import Gleap, { GleapSession } from './Gleap'; const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); @@ -14,7 +15,7 @@ describe('Gleap.startProductTour redirect to the start URL', () => { const startFrom = async (currentUrl, config) => { delete window.location; window.location = { href: currentUrl }; - configSpy = jest.spyOn(GleapSession.getInstance(), 'startProductTourConfig').mockResolvedValue(config); + configSpy = vi.spyOn(GleapSession.getInstance(), 'startProductTourConfig').mockResolvedValue(config); Gleap.startProductTour('tour-1', true); await flush(); return new URL(window.location.href); diff --git a/src/GleapRegions.test.js b/src/GleapRegions.test.js index 9c2b2450..7499e702 100644 --- a/src/GleapRegions.test.js +++ b/src/GleapRegions.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest'; import Gleap, { GleapBannerManager, GleapFrameManager, GleapModalManager, GleapSession } from './Gleap'; import GleapNetworkIntercepter from './GleapNetworkIntercepter'; import { GLEAP_DEFAULT_REGION, GLEAP_REGIONS, resolveGleapRegion } from './GleapRegions'; @@ -37,7 +38,7 @@ let warnSpy; beforeEach(() => { // Fresh session singleton per test so the defaults are observable. GleapSession.instance = undefined; - warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {}); + warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); }); afterEach(() => { @@ -181,7 +182,7 @@ describe('region side effects', () => { test('setAgentConversationUrl applies to newly attached agent conversations', () => { // The iframe bootstrap fetches the frame document; keep it pending. - global.fetch = jest.fn(() => new Promise(() => {})); + global.fetch = vi.fn(() => new Promise(() => {})); const create = () => { const element = document.createElement('gleap-agent-conversation'); diff --git a/src/GleapReplayRecorder.test.js b/src/GleapReplayRecorder.test.js index 9db7543b..bb1be80b 100644 --- a/src/GleapReplayRecorder.test.js +++ b/src/GleapReplayRecorder.test.js @@ -1,10 +1,11 @@ +import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest'; import { record } from '@rrweb/record'; import GleapReplayRecorder, { approximateSize } from './GleapReplayRecorder'; // The recorder only needs rrweb's emit callback; tests drive it directly. -jest.mock('@rrweb/record', () => ({ record: jest.fn() })); -jest.mock('@rrweb/packer', () => ({ pack: (event) => event })); -jest.mock('./GleapHelper', () => ({ isMobile: () => false })); +vi.mock('@rrweb/record', () => ({ record: vi.fn() })); +vi.mock('@rrweb/packer', () => ({ pack: (event) => event })); +vi.mock('./GleapHelper', () => ({ isMobile: () => false })); const MB = 1024 * 1024; const META = 4; @@ -42,17 +43,17 @@ const bufferedHrefs = (recorder) => .map((event) => event.data.href); beforeEach(() => { - jest.useFakeTimers(); + vi.useFakeTimers(); record.mockReset().mockImplementation((options) => { emit = options.emit; - return jest.fn(); + return vi.fn(); }); - record.takeFullSnapshot = jest.fn((isCheckout) => checkpoint('forced', MB, isCheckout)); + record.takeFullSnapshot = vi.fn((isCheckout) => checkpoint('forced', MB, isCheckout)); global.window = { location: { origin: 'https://app.example.com' }, innerWidth: 1920, innerHeight: 1080 }; }); afterEach(() => { - jest.useRealTimers(); + vi.useRealTimers(); delete global.window; }); @@ -91,7 +92,7 @@ describe('replay buffer byte budget (#147738)', () => { for (let i = 0; i < 4; i++) emit(mutation(3 * MB)); expect(record.takeFullSnapshot).not.toHaveBeenCalled(); - jest.advanceTimersByTime(0); + vi.advanceTimersByTime(0); expect(record.takeFullSnapshot).toHaveBeenCalledTimes(1); expect(record.takeFullSnapshot).toHaveBeenCalledWith(true); @@ -103,13 +104,13 @@ describe('replay buffer byte budget (#147738)', () => { startRecorder(); checkpoint('first', MB, false); for (let i = 0; i < 4; i++) emit(mutation(3 * MB)); - jest.advanceTimersByTime(0); + vi.advanceTimersByTime(0); for (let i = 0; i < 4; i++) emit(mutation(3 * MB)); - jest.advanceTimersByTime(29 * 1000); + vi.advanceTimersByTime(29 * 1000); expect(record.takeFullSnapshot).toHaveBeenCalledTimes(1); - jest.advanceTimersByTime(1000); + vi.advanceTimersByTime(1000); expect(record.takeFullSnapshot).toHaveBeenCalledTimes(2); }); @@ -118,7 +119,7 @@ describe('replay buffer byte budget (#147738)', () => { checkpoint('first', 12 * MB, false); emit(mutation(MB)); - jest.advanceTimersByTime(10 * 60 * 1000); + vi.advanceTimersByTime(10 * 60 * 1000); expect(record.takeFullSnapshot).not.toHaveBeenCalled(); expect(bufferedHrefs(recorder)).toEqual(['first']); @@ -130,7 +131,7 @@ describe('replay buffer byte budget (#147738)', () => { for (let i = 0; i < 4; i++) emit(mutation(3 * MB)); recorder.stop(); - jest.advanceTimersByTime(60 * 1000); + vi.advanceTimersByTime(60 * 1000); expect(record.takeFullSnapshot).not.toHaveBeenCalled(); }); @@ -154,7 +155,7 @@ describe('input masking options passed to rrweb', () => { }); test("a site's maskInputOptions keep their kinds; its maskInputFn is wrapped, not replaced", () => { - const siteMaskInputFn = jest.fn(() => 'masked by site'); + const siteMaskInputFn = vi.fn(() => 'masked by site'); const options = recordOptions({ maskInputOptions: { select: true }, maskInputFn: siteMaskInputFn }); expect(options.maskInputOptions.select).toBe(true); @@ -213,7 +214,7 @@ describe('approximateSize', () => { timestamp: 1790000000000, }, ], - ])('%s -> within 25%% of its serialized size', (_label, event) => { + ])('%s -> within 25% of its serialized size', (_label, event) => { const ratio = approximateSize(event) / JSON.stringify(event).length; expect(ratio).toBeGreaterThan(0.75); expect(ratio).toBeLessThan(1.25); @@ -227,11 +228,11 @@ describe('startIfNotRunning waits for an idle moment', () => { beforeEach(() => { idleCallbacks = []; - global.window.requestIdleCallback = jest.fn((callback, options) => { + global.window.requestIdleCallback = vi.fn((callback, options) => { idleCallbacks.push({ callback, options }); return idleCallbacks.length; }); - global.window.cancelIdleCallback = jest.fn((handle) => { + global.window.cancelIdleCallback = vi.fn((handle) => { idleCallbacks[handle - 1].cancelled = true; }); }); @@ -297,7 +298,7 @@ describe('startIfNotRunning waits for an idle moment', () => { recorder.startIfNotRunning(); expect(record).not.toHaveBeenCalled(); - jest.advanceTimersByTime(2000); + vi.advanceTimersByTime(2000); expect(record).toHaveBeenCalledTimes(1); }); }); diff --git a/src/GleapScreenRecorder.test.js b/src/GleapScreenRecorder.test.js index 4b4b6b7e..1dece9ac 100644 --- a/src/GleapScreenRecorder.test.js +++ b/src/GleapScreenRecorder.test.js @@ -1,34 +1,35 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { test, expect, vi, beforeEach } from 'vitest'; import { GleapScreenRecorder } from './GleapScreenRecorder'; import { requestDisplayStream } from './GleapCaptureRecorder'; import { hasDisplayMedia, isDesktopChromium } from './GleapCaptureSettings'; +import { stopStream } from './GleapCaptureScreenshot'; // The feedback form's recorder runs on the capture requests' recording engine (#228450). const mockRecordings = []; -jest.mock('./GleapSession', () => ({ __esModule: true, default: { getInstance: () => ({}) } })); -jest.mock('./GleapCaptureScreenshot', () => ({ stopStream: jest.fn() })); -jest.mock('./GleapCaptureSettings', () => ({ - hasDisplayMedia: jest.fn(() => true), - isDesktopChromium: jest.fn(() => true), +vi.mock('./GleapSession', () => ({ __esModule: true, default: { getInstance: () => ({}) } })); +vi.mock('./GleapCaptureScreenshot', () => ({ stopStream: vi.fn() })); +vi.mock('./GleapCaptureSettings', () => ({ + hasDisplayMedia: vi.fn(() => true), + isDesktopChromium: vi.fn(() => true), })); -jest.mock('./GleapCaptureRecorder', () => ({ - requestDisplayStream: jest.fn(), +vi.mock('./GleapCaptureRecorder', () => ({ + requestDisplayStream: vi.fn(), DisplayRecording: class { constructor(options) { this.options = options; - this.start = jest.fn(() => Promise.resolve({ hasMicrophone: true })); - this.stop = jest.fn(); - this.cancel = jest.fn(); - this.setMicrophoneEnabled = jest.fn(); + this.start = vi.fn(() => Promise.resolve({ hasMicrophone: true })); + this.stop = vi.fn(); + this.cancel = vi.fn(); + this.setMicrophoneEnabled = vi.fn(); mockRecordings.push(this); } }, })); -const { stopStream } = jest.requireMock('./GleapCaptureScreenshot'); const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); const STREAM = { id: 'tab-stream' }; @@ -37,13 +38,13 @@ const createRecorder = () => new GleapScreenRecorder(rerender, 'No access to the beforeEach(() => { mockRecordings.length = 0; - rerender = jest.fn(); + rerender = vi.fn(); hasDisplayMedia.mockReturnValue(true); isDesktopChromium.mockReturnValue(true); requestDisplayStream.mockReset().mockReturnValue(Promise.resolve(STREAM)); stopStream.mockClear(); - window.alert = jest.fn(); - URL.createObjectURL = jest.fn(() => 'blob:preview'); + window.alert = vi.fn(); + URL.createObjectURL = vi.fn(() => 'blob:preview'); document.body.innerHTML = '
' + '
'; diff --git a/src/GleapSession.test.js b/src/GleapSession.test.js index 6bc03067..6da5ae9c 100644 --- a/src/GleapSession.test.js +++ b/src/GleapSession.test.js @@ -1,49 +1,51 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import GleapSession from './GleapSession'; import { saveToGleapCache, loadFromGleapCache, setGleapCookie, eraseGleapCookie, getGleapCookie } from './GleapHelper'; +import { GleapFrameManager } from './Gleap'; // The session manager only needs the sibling managers to exist; none of the // paths under test depend on their behavior beyond being callable. -jest.mock('./Gleap', () => ({ - GleapBannerManager: { getInstance: jest.fn(() => ({ removeBannerUI: jest.fn() })) }, - GleapEventManager: { notifyEvent: jest.fn() }, +vi.mock('./Gleap', () => ({ + GleapBannerManager: { getInstance: vi.fn(() => ({ removeBannerUI: vi.fn() })) }, + GleapEventManager: { notifyEvent: vi.fn() }, GleapFrameManager: { - getInstance: jest.fn(() => ({ sendMessage: jest.fn(), sendSessionUpdate: jest.fn() })), + getInstance: vi.fn(() => ({ sendMessage: vi.fn(), sendSessionUpdate: vi.fn() })), }, - GleapModalManager: { getInstance: jest.fn(() => ({ hideModal: jest.fn() })) }, + GleapModalManager: { getInstance: vi.fn(() => ({ hideModal: vi.fn() })) }, GleapNotificationManager: { - getInstance: jest.fn(() => ({ clearAllNotifications: jest.fn(), setNotificationCount: jest.fn() })), + getInstance: vi.fn(() => ({ clearAllNotifications: vi.fn(), setNotificationCount: vi.fn() })), }, - GleapStreamedEvent: { getInstance: jest.fn(() => ({ restart: jest.fn(), stop: jest.fn() })) }, - GleapTranslationManager: { getInstance: jest.fn(() => ({ getActiveLanguage: () => 'en' })) }, + GleapStreamedEvent: { getInstance: vi.fn(() => ({ restart: vi.fn(), stop: vi.fn() })) }, + GleapTranslationManager: { getInstance: vi.fn(() => ({ getActiveLanguage: () => 'en' })) }, })); -jest.mock('./ChecklistNetworkManager', () => ({ +vi.mock('./ChecklistNetworkManager', () => ({ __esModule: true, - default: { getInstance: jest.fn(() => ({ clearCache: jest.fn() })) }, + default: { getInstance: vi.fn(() => ({ clearCache: vi.fn() })) }, })); -jest.mock('./AgentNetworkManager', () => ({ +vi.mock('./AgentNetworkManager', () => ({ __esModule: true, - default: { getInstance: jest.fn(() => ({ clearCache: jest.fn() })) }, + default: { getInstance: vi.fn(() => ({ clearCache: vi.fn() })) }, })); -jest.mock('./GleapTooltipManager', () => ({ +vi.mock('./GleapTooltipManager', () => ({ __esModule: true, - default: { getInstance: jest.fn(() => ({ destroy: jest.fn(), load: jest.fn() })) }, + default: { getInstance: vi.fn(() => ({ destroy: vi.fn(), load: vi.fn() })) }, })); -jest.mock('./GleapAiChatbarManager', () => ({ +vi.mock('./GleapAiChatbarManager', () => ({ __esModule: true, default: { instance: null }, })); -jest.mock('./GleapHelper', () => ({ - eraseGleapCookie: jest.fn(), - getDeviceType: jest.fn(() => 'desktop'), - getGleapCookie: jest.fn(() => null), - loadFromGleapCache: jest.fn(() => null), - saveToGleapCache: jest.fn(), - setGleapCookie: jest.fn(), +vi.mock('./GleapHelper', () => ({ + eraseGleapCookie: vi.fn(), + getDeviceType: vi.fn(() => 'desktop'), + getGleapCookie: vi.fn(() => null), + loadFromGleapCache: vi.fn(() => null), + saveToGleapCache: vi.fn(), + setGleapCookie: vi.fn(), })); // Minimal XHR double: tests drive responses explicitly via respond()/error(). @@ -109,12 +111,12 @@ const buildSession = () => { }; beforeEach(() => { - jest.useFakeTimers(); + vi.useFakeTimers(); MockXhr.instances = []; global.XMLHttpRequest = MockXhr; // No dispatchEvent on purpose: validateSession guards on its existence, and // node has no CustomEvent to construct. - global.window = { addEventListener: jest.fn() }; + global.window = { addEventListener: vi.fn() }; cacheStore = {}; loadFromGleapCache.mockReset().mockImplementation((key) => (key in cacheStore ? cacheStore[key] : null)); saveToGleapCache.mockReset().mockImplementation((key, value) => { @@ -123,7 +125,7 @@ beforeEach(() => { }); afterEach(() => { - jest.useRealTimers(); + vi.useRealTimers(); }); describe('startSession failure handling', () => { @@ -143,7 +145,7 @@ describe('startSession failure handling', () => { expect(saveToGleapCache).not.toHaveBeenCalledWith(expect.anything(), null); // The retry re-sends the same session credentials. - jest.advanceTimersByTime(10 * 1000); + vi.advanceTimersByTime(10 * 1000); const retry = MockXhr.instances[1]; expect(retry).toBeDefined(); expect(retry.headers['Gleap-Id']).toBe('gleap-id-1'); @@ -162,7 +164,7 @@ describe('startSession failure handling', () => { expect(saveToGleapCache).toHaveBeenCalledWith(expect.anything(), null); // Retry happens without stale credentials. - jest.advanceTimersByTime(0); + vi.advanceTimersByTime(0); const retry = MockXhr.instances[1]; expect(retry).toBeDefined(); expect(retry.headers['Gleap-Id']).toBeUndefined(); @@ -175,7 +177,7 @@ describe('startSession failure handling', () => { MockXhr.instances[0].respond(503); expect(session.session.gleapId).toBe(null); - jest.advanceTimersByTime(0); + vi.advanceTimersByTime(0); expect(MockXhr.instances.length).toBe(2); }); @@ -187,7 +189,7 @@ describe('startSession failure handling', () => { MockXhr.instances[0].respond(429); expect(session.session.gleapId).toBe('gleap-id-1'); - jest.advanceTimersByTime(60 * 60 * 1000); + vi.advanceTimersByTime(60 * 60 * 1000); expect(MockXhr.instances.length).toBe(1); }); }); @@ -351,7 +353,7 @@ describe('user switch in the same browser', () => { session.startSession(); session.identifySession('user-2', { email: 'other@example.com' }); - const started = jest.fn(() => session.session.userId); + const started = vi.fn(() => session.session.userId); session.onContactSettled(started); expect(started).not.toHaveBeenCalled(); @@ -373,9 +375,9 @@ describe('authenticated file sessions', () => { const session = buildSession(); session.lastIdentify = { userId: 'user-1', userData: {}, userHash: 'verified-hmac' }; session.validateSession({ ...CACHED_IDENTIFIED_SESSION, fileAccessToken: 'file-session', fileAccessExpiresAt: new Date(Date.now() + 900000).toISOString() }); - jest.advanceTimersByTime(300000); + vi.advanceTimersByTime(300000); session.validateSession({ ...CACHED_IDENTIFIED_SESSION }); - jest.advanceTimersByTime(300000); + vi.advanceTimersByTime(300000); expect(identifyRequests()).toHaveLength(1); }); it('re-verifies an unchanged cached identity when the project now requires authenticated files', () => { @@ -397,7 +399,7 @@ describe('authenticated file sessions', () => { const session = buildSession(); session.lastIdentify = { userId: 'user-1', userData: { email: 'bec@example.com' }, userHash: 'verified-hmac' }; session.validateSession({ ...CACHED_IDENTIFIED_SESSION, fileAccessToken: 'file-session', fileAccessExpiresAt: new Date(Date.now() + 900000).toISOString() }); - jest.advanceTimersByTime(600000); + vi.advanceTimersByTime(600000); expect(identifyRequests()).toHaveLength(1); expect(JSON.parse(identifyRequests()[0].body).userHash).toBe('verified-hmac'); }); @@ -426,7 +428,7 @@ describe('identity tokens (setUserJwt)', () => { let warn; beforeEach(() => { - warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); }); afterEach(() => { warn.mockRestore(); @@ -516,7 +518,7 @@ describe('identity tokens (setUserJwt)', () => { it('on token_expired asks the provider once and retries with the new token', async () => { const session = readySession(); const fresh = jwtOf({ userId: 'user-1', exp: inSeconds(3600) }); - const provider = jest.fn(() => Promise.resolve(fresh)); + const provider = vi.fn(() => Promise.resolve(fresh)); session.setUserJwtProvider(provider); const done = session.setUserJwt(jwtOf({ userId: 'user-1', exp: inSeconds(-10) })); @@ -533,7 +535,7 @@ describe('identity tokens (setUserJwt)', () => { it('retries only once and shares one provider call', async () => { const session = readySession(); - const provider = jest.fn(() => Promise.resolve(jwtOf({ userId: 'user-1', exp: inSeconds(3600) }))); + const provider = vi.fn(() => Promise.resolve(jwtOf({ userId: 'user-1', exp: inSeconds(3600) }))); session.setUserJwtProvider(provider); const done = session.setUserJwt(jwtOf({ userId: 'user-1', exp: inSeconds(-10) })); @@ -550,13 +552,13 @@ describe('identity tokens (setUserJwt)', () => { it('pauses 30 s after a provider failure', async () => { const session = buildSession(); - const provider = jest.fn(() => Promise.reject(new Error('offline'))); + const provider = vi.fn(() => Promise.reject(new Error('offline'))); session.setUserJwtProvider(provider); expect(await session.requestUserJwt()).toBeNull(); expect(await session.requestUserJwt()).toBeNull(); expect(provider).toHaveBeenCalledTimes(1); - jest.advanceTimersByTime(30 * 1000); + vi.advanceTimersByTime(30 * 1000); await session.requestUserJwt(); expect(provider).toHaveBeenCalledTimes(2); }); @@ -565,7 +567,7 @@ describe('identity tokens (setUserJwt)', () => { const session = buildSession(); session.setUserJwtProvider(() => new Promise(() => {})); const pending = session.requestUserJwt(); - jest.advanceTimersByTime(10 * 1000); + vi.advanceTimersByTime(10 * 1000); expect(await pending).toBeNull(); }); @@ -584,12 +586,12 @@ describe('identity tokens (setUserJwt)', () => { it('asks the provider before a file-access renewal when the token expires within 5 minutes', async () => { const session = buildSession(); const fresh = jwtOf({ userId: 'user-1', exp: inSeconds(3600) }); - const provider = jest.fn(() => fresh); + const provider = vi.fn(() => fresh); session.setUserJwtProvider(provider); session.lastIdentify = { userId: 'user-1', userData: {}, userHash: jwtOf({ userId: 'user-1', exp: inSeconds(60) }) }; session.validateSession({ ...CACHED_IDENTIFIED_SESSION, fileAccessToken: 'file-session', fileAccessExpiresAt: new Date(Date.now() + 900000).toISOString() }); - jest.advanceTimersByTime(600000); + vi.advanceTimersByTime(600000); await flush(); expect(provider).toHaveBeenCalledTimes(1); expect(identifyRequests()).toHaveLength(1); @@ -598,7 +600,7 @@ describe('identity tokens (setUserJwt)', () => { it('clearIdentity drops the token and auth tokens but keeps the provider', () => { const session = readySession(); - const provider = jest.fn(); + const provider = vi.fn(); session.setUserJwtProvider(provider); session.setUserJwt(jwtOf({ userId: 'user-1' })); session.authTokens = { backend: 'secret' }; @@ -613,7 +615,7 @@ describe('auth tokens (setAuthTokens)', () => { const authTokenRequests = () => MockXhr.instances.filter((xhr) => xhr.url && xhr.url.endsWith('/sessions/auth-tokens')); let warn; beforeEach(() => { - warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); }); afterEach(() => { warn.mockRestore(); @@ -694,7 +696,7 @@ describe('grant (signed session credential)', () => { let warn; beforeEach(() => { - warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); setGleapCookie.mockClear(); eraseGleapCookie.mockClear(); getGleapCookie.mockReset().mockImplementation(() => null); @@ -754,7 +756,7 @@ describe('grant (signed session credential)', () => { const session = readySession(); session.setUserJwt(jwtOf({ userId: 'user-1', exp: inSeconds(3600) })); respondWithGrant(identifyRequests()[0], grantFor('gleap-id-1')); - const provider = jest.fn(); + const provider = vi.fn(); session.setUserJwtProvider(provider); session.clearSession(0, false); expect(session.grant).toBe(null); @@ -811,9 +813,9 @@ describe('grant (signed session credential)', () => { it('renews a minute before the grant lifetime ends, counted from receipt', async () => { const session = readySession(); signIn(session, shortGrant(3600)); - jest.advanceTimersByTime(3540 * 1000 - 1); + vi.advanceTimersByTime(3540 * 1000 - 1); expect(identifyRequests()).toHaveLength(1); - jest.advanceTimersByTime(1); + vi.advanceTimersByTime(1); await flush(); expect(identifyRequests()).toHaveLength(2); }); @@ -821,20 +823,20 @@ describe('grant (signed session credential)', () => { it('a 60-70 s grant waits 30 s and renews at most once a minute (no loop)', async () => { const session = readySession(); signIn(session, shortGrant(65)); - jest.advanceTimersByTime(29 * 1000); + vi.advanceTimersByTime(29 * 1000); expect(identifyRequests()).toHaveLength(1); - jest.advanceTimersByTime(1000); + vi.advanceTimersByTime(1000); await flush(); expect(identifyRequests()).toHaveLength(2); // The refresh answers with another short grant: the next refresh waits for the minute. - jest.advanceTimersByTime(1000); + vi.advanceTimersByTime(1000); respondWithGrant(identifyRequests()[1], shortGrant(65, 1)); await flush(); - jest.advanceTimersByTime(30 * 1000); + vi.advanceTimersByTime(30 * 1000); await flush(); expect(identifyRequests()).toHaveLength(2); - jest.advanceTimersByTime(29 * 1000); + vi.advanceTimersByTime(29 * 1000); await flush(); expect(identifyRequests()).toHaveLength(3); }); @@ -843,10 +845,10 @@ describe('grant (signed session credential)', () => { const session = readySession(); // Issued by a server whose clock is two hours behind the device: exp already lies in the device's past. signIn(session, shortGrant(3600, -7200)); - jest.advanceTimersByTime(60 * 1000); + vi.advanceTimersByTime(60 * 1000); await flush(); expect(identifyRequests()).toHaveLength(1); - jest.advanceTimersByTime(3480 * 1000); + vi.advanceTimersByTime(3480 * 1000); await flush(); expect(identifyRequests()).toHaveLength(2); }); @@ -854,13 +856,13 @@ describe('grant (signed session credential)', () => { it('skips while a refresh is in flight', async () => { const session = readySession(); signIn(session, shortGrant(65)); - jest.advanceTimersByTime(30 * 1000); + vi.advanceTimersByTime(30 * 1000); await flush(); expect(identifyRequests()).toHaveLength(2); expect(session.grantRefreshInFlight).toBe(true); // Re-arming for the same grant while the refresh runs sends nothing more. session.armGrantRefresh(session.grant, Date.now()); - jest.advanceTimersByTime(120 * 1000); + vi.advanceTimersByTime(120 * 1000); await flush(); expect(identifyRequests()).toHaveLength(2); identifyRequests()[1].error(); @@ -871,15 +873,15 @@ describe('grant (signed session credential)', () => { it('a failed refresh is tried again a minute later', async () => { const session = readySession(); signIn(session, shortGrant(65)); - jest.advanceTimersByTime(30 * 1000); + vi.advanceTimersByTime(30 * 1000); await flush(); expect(identifyRequests()).toHaveLength(2); identifyRequests()[1].error(); await flush(); - jest.advanceTimersByTime(59 * 1000); + vi.advanceTimersByTime(59 * 1000); await flush(); expect(identifyRequests()).toHaveLength(2); - jest.advanceTimersByTime(1000); + vi.advanceTimersByTime(1000); await flush(); expect(identifyRequests()).toHaveLength(3); }); @@ -916,7 +918,7 @@ describe('grant (signed session credential)', () => { session.setUserJwt(token()); session.startSession(); sessionsRequests()[1].respond(200, JSON.stringify({ ...CACHED_IDENTIFIED_SESSION, ...SIGNED_MODE })); - jest.advanceTimersByTime(10 * 60 * 1000); + vi.advanceTimersByTime(10 * 60 * 1000); expect(identifyRequests()).toHaveLength(1); }); @@ -938,7 +940,7 @@ describe('grant (signed session credential)', () => { expect(session.hasLiveGrant()).toBe(true); eraseGleapCookie.mockClear(); MockXhr.instances = []; - jest.advanceTimersByTime(60 * 1000); + vi.advanceTimersByTime(60 * 1000); // The grant still looks live locally, but the server no longer accepts it. session.startSession(); @@ -955,7 +957,7 @@ describe('grant (signed session credential)', () => { identifyRequests()[0].respond(200, JSON.stringify({ ...CACHED_IDENTIFIED_SESSION, identity: { signed: false, mode: 'signed' } })); session.startSession(); sessionsRequests()[1].respond(200, JSON.stringify({ ...CACHED_IDENTIFIED_SESSION, identity: { signed: false, mode: 'signed' } })); - jest.advanceTimersByTime(10 * 60 * 1000); + vi.advanceTimersByTime(10 * 60 * 1000); expect(identifyRequests()).toHaveLength(1); }); @@ -991,7 +993,7 @@ describe('grant (signed session credential)', () => { it('asks the provider once and identifies with its token, which brings the grant back', async () => { const token = jwtOf({ userId: 'user-1', exp: inSeconds(3600) }); - const provider = jest.fn(() => Promise.resolve(token)); + const provider = vi.fn(() => Promise.resolve(token)); const session = reloadWithProvider(provider); expect(provider).not.toHaveBeenCalled(); @@ -1011,7 +1013,7 @@ describe('grant (signed session credential)', () => { }); it('no loop: at most one provider call and one identify per session load', async () => { - const provider = jest.fn(() => Promise.resolve(jwtOf({ userId: 'user-1', exp: inSeconds(3600) }))); + const provider = vi.fn(() => Promise.resolve(jwtOf({ userId: 'user-1', exp: inSeconds(3600) }))); const session = reloadWithProvider(provider); answerSignedMode(sessionsRequests()[0]); await flush(); @@ -1023,7 +1025,7 @@ describe('grant (signed session credential)', () => { session.startSession(); answerSignedMode(sessionsRequests()[1]); await flush(); - jest.advanceTimersByTime(10 * 60 * 1000); + vi.advanceTimersByTime(10 * 60 * 1000); session.startSession(); answerSignedMode(sessionsRequests()[2]); await flush(); @@ -1033,7 +1035,7 @@ describe('grant (signed session credential)', () => { it('one call at a time: a second signed-mode answer while the provider runs asks nothing more', async () => { let resolveToken; - const provider = jest.fn(() => new Promise((resolve) => (resolveToken = resolve))); + const provider = vi.fn(() => new Promise((resolve) => (resolveToken = resolve))); const session = reloadWithProvider(provider); answerSignedMode(sessionsRequests()[0]); session.startSession(); @@ -1054,7 +1056,7 @@ describe('grant (signed session credential)', () => { }); it('the provider returns null: nothing is sent, nothing logged, and it is not asked again this load', async () => { - const provider = jest.fn(() => null); + const provider = vi.fn(() => null); const session = reloadWithProvider(provider); answerSignedMode(sessionsRequests()[0]); await flush(); @@ -1062,7 +1064,7 @@ describe('grant (signed session credential)', () => { expect(identifyRequests()).toHaveLength(0); expect(warn).not.toHaveBeenCalled(); - jest.advanceTimersByTime(10 * 60 * 1000); + vi.advanceTimersByTime(10 * 60 * 1000); session.startSession(); answerSignedMode(sessionsRequests()[1]); await flush(); @@ -1072,7 +1074,7 @@ describe('grant (signed session credential)', () => { it('a token for another user goes through identity_mismatch (fresh visitor, identify once more)', async () => { const token = jwtOf({ userId: 'user-2', exp: inSeconds(3600) }); - const provider = jest.fn(() => token); + const provider = vi.fn(() => token); const session = reloadWithProvider(provider); answerSignedMode(sessionsRequests()[0]); await flush(); @@ -1094,7 +1096,7 @@ describe('grant (signed session credential)', () => { }); it('a provider set after the /sessions answer is still asked once', async () => { - const provider = jest.fn(() => jwtOf({ userId: 'user-1', exp: inSeconds(3600) })); + const provider = vi.fn(() => jwtOf({ userId: 'user-1', exp: inSeconds(3600) })); const session = reloadWithProvider(null); answerSignedMode(sessionsRequests()[0]); await flush(); @@ -1108,7 +1110,7 @@ describe('grant (signed session credential)', () => { }); it('does not ask for a Classic answer, an anonymous session, a live grant or a held token', async () => { - const provider = jest.fn(() => jwtOf({ userId: 'user-1', exp: inSeconds(3600) })); + const provider = vi.fn(() => jwtOf({ userId: 'user-1', exp: inSeconds(3600) })); reloadWithProvider(provider); sessionsRequests()[0].respond(200, JSON.stringify({ ...CACHED_IDENTIFIED_SESSION })); @@ -1138,7 +1140,7 @@ describe('grant (signed session credential)', () => { it('a logout while the provider runs drops its token', async () => { let resolveToken; - const provider = jest.fn(() => new Promise((resolve) => (resolveToken = resolve))); + const provider = vi.fn(() => new Promise((resolve) => (resolveToken = resolve))); const session = reloadWithProvider(provider); answerSignedMode(sessionsRequests()[0]); await flush(); @@ -1151,7 +1153,6 @@ describe('grant (signed session credential)', () => { }); describe('signed session expiry (a visitor afterwards, like Intercom on the web)', () => { - const { GleapFrameManager } = require('./Gleap'); const UNSIGNED_SIGNED_MODE = { identity: { signed: false, grant: null, mode: 'signed' } }; const sessionsRequests = () => MockXhr.instances.filter((xhr) => xhr.url.endsWith('/sessions')); const answerUnsigned = (xhr) => xhr.respond(200, JSON.stringify({ ...CACHED_IDENTIFIED_SESSION, ...UNSIGNED_SIGNED_MODE })); @@ -1159,11 +1160,11 @@ describe('grant (signed session credential)', () => { let info; beforeEach(() => { - info = jest.spyOn(console, 'info').mockImplementation(() => {}); + info = vi.spyOn(console, 'info').mockImplementation(() => {}); }); afterEach(() => { info.mockRestore(); - GleapFrameManager.getInstance.mockImplementation(() => ({ sendMessage: jest.fn(), sendSessionUpdate: jest.fn() })); + GleapFrameManager.getInstance.mockImplementation(() => ({ sendMessage: vi.fn(), sendSessionUpdate: vi.fn() })); }); // Signs user-1 in on gleap-id-1 with a grant that runs out in `grantSeconds`. @@ -1176,8 +1177,8 @@ describe('grant (signed session credential)', () => { // The page is closed, then reopened `laterSeconds` on; the grant cookie expired with the grant. const reloadLater = (laterSeconds, setup = () => {}) => { - jest.clearAllTimers(); - jest.setSystemTime(Date.now() + laterSeconds * 1000); + vi.clearAllTimers(); + vi.setSystemTime(Date.now() + laterSeconds * 1000); MockXhr.instances = []; const session = buildSession(); setup(session); @@ -1193,7 +1194,7 @@ describe('grant (signed session credential)', () => { expect(cacheStore['session-sdk-key']).toBe(null); expect(cacheStore['signed-session-sdk-key']).toBe(null); expect(session.lastIdentify).toBe(null); - jest.advanceTimersByTime(0); + vi.advanceTimersByTime(0); const fresh = sessionsRequests()[sessionsRequests().length - 1]; expect(fresh.headers['Gleap-Id']).toBeUndefined(); fresh.respond(200, JSON.stringify({ gleapId: 'gleap-id-guest', gleapHash: 'gleap-hash-guest' })); @@ -1219,7 +1220,7 @@ describe('grant (signed session credential)', () => { expect(identifyRequests()).toHaveLength(0); expect(info).toHaveBeenCalledWith(expect.stringContaining('continues as a visitor')); // The visitor session is final: nothing more is sent. - jest.advanceTimersByTime(10 * 60 * 1000); + vi.advanceTimersByTime(10 * 60 * 1000); await flush(); expect(sessionsRequests()).toHaveLength(2); expect(identifyRequests()).toHaveLength(0); @@ -1245,7 +1246,7 @@ describe('grant (signed session credential)', () => { it('a JWT provider with a fresh token keeps the user signed (asked once)', async () => { signedIn(600); const fresh = token(); - const provider = jest.fn(() => Promise.resolve(fresh)); + const provider = vi.fn(() => Promise.resolve(fresh)); const session = reloadLater(11 * 60, (s) => s.setUserJwtProvider(provider)); answerUnsigned(sessionsRequests()[0]); await flush(); @@ -1262,7 +1263,7 @@ describe('grant (signed session credential)', () => { it('a JWT provider that returns null: the session ends (provider asked once, kept afterwards)', async () => { signedIn(600); - const provider = jest.fn(() => null); + const provider = vi.fn(() => null); const session = reloadLater(11 * 60, (s) => s.setUserJwtProvider(provider)); answerUnsigned(sessionsRequests()[0]); await expectVisitor(session); @@ -1278,7 +1279,7 @@ describe('grant (signed session credential)', () => { expect(identifyRequests()).toHaveLength(1); answerUnsigned(sessionsRequests()[0]); await flush(); - jest.advanceTimersByTime(30 * 1000); + vi.advanceTimersByTime(30 * 1000); await flush(); expect(session.session.gleapId).toBe('gleap-id-1'); respondWithGrant(identifyRequests()[0], grantFor('gleap-id-1')); @@ -1312,7 +1313,7 @@ describe('grant (signed session credential)', () => { answerUnsigned(sessionsRequests()[0]); identifyRequests()[0].error(); await flush(); - jest.advanceTimersByTime(60 * 1000); + vi.advanceTimersByTime(60 * 1000); await flush(); expect(session.session.gleapId).toBe('gleap-id-1'); expect(session.session.userId).toBe('user-1'); @@ -1328,7 +1329,7 @@ describe('grant (signed session credential)', () => { const session = reloadLater(30 * 24 * 3600); answerUnsigned(sessionsRequests()[0]); await flush(); - jest.advanceTimersByTime(60 * 1000); + vi.advanceTimersByTime(60 * 1000); expect(session.session.gleapId).toBe('gleap-id-1'); expect(session.session.userId).toBe('user-1'); expect(info).not.toHaveBeenCalled(); @@ -1339,7 +1340,7 @@ describe('grant (signed session credential)', () => { const session = reloadLater(5 * 60); answerUnsigned(sessionsRequests()[0]); await flush(); - jest.advanceTimersByTime(0); + vi.advanceTimersByTime(0); expect(session.session.gleapId).toBe('gleap-id-1'); expect(session.session.userId).toBe('user-1'); expect(info).not.toHaveBeenCalled(); @@ -1350,7 +1351,7 @@ describe('grant (signed session credential)', () => { const session = reloadLater(11 * 60); sessionsRequests()[0].respond(200, JSON.stringify({ ...CACHED_IDENTIFIED_SESSION })); await flush(); - jest.advanceTimersByTime(0); + vi.advanceTimersByTime(0); expect(session.session.userId).toBe('user-1'); expect(info).not.toHaveBeenCalled(); }); @@ -1369,7 +1370,7 @@ describe('grant (signed session credential)', () => { expect(session.signedSessionExpiryTimeout).not.toBe(null); session.lastIdentify = null; MockXhr.instances = []; - jest.advanceTimersByTime(600 * 1000); + vi.advanceTimersByTime(600 * 1000); await flush(); expect(sessionsRequests()).toHaveLength(1); }); @@ -1387,14 +1388,14 @@ describe('grant (signed session credential)', () => { // Token valid 5 min, grant 10 min, no provider: the refresh a minute before the end sends the expired token. const session = signedIn(600, 300); MockXhr.instances = []; - jest.advanceTimersByTime(540 * 1000); + vi.advanceTimersByTime(540 * 1000); await flush(); expect(identifyRequests()).toHaveLength(1); identifyRequests()[0].respond(401, JSON.stringify({ detail: { value: 'token_expired' } })); await flush(); expect(sessionsRequests()).toHaveLength(0); - jest.advanceTimersByTime(60 * 1000); + vi.advanceTimersByTime(60 * 1000); await flush(); expect(sessionsRequests()).toHaveLength(1); expect(sessionsRequests()[0].headers['Gleap-Id']).toBe('gleap-id-1'); @@ -1407,10 +1408,10 @@ describe('grant (signed session credential)', () => { it('a renewed grant re-arms the check: nothing ends', async () => { const session = signedIn(600); MockXhr.instances = []; - jest.advanceTimersByTime(540 * 1000); + vi.advanceTimersByTime(540 * 1000); await flush(); respondWithGrant(identifyRequests()[0], grantFor('gleap-id-1', inSeconds(600))); - jest.advanceTimersByTime(120 * 1000); + vi.advanceTimersByTime(120 * 1000); await flush(); expect(sessionsRequests()).toHaveLength(0); expect(session.hasLiveGrant()).toBe(true); @@ -1422,7 +1423,7 @@ describe('grant (signed session credential)', () => { const renewed = grantFor('gleap-id-1', inSeconds(1800)); getGleapCookie.mockImplementation((name) => (name === 'gleap-grant-sdk-key' ? encodeURIComponent(renewed) : null)); MockXhr.instances = []; - jest.advanceTimersByTime(600 * 1000); + vi.advanceTimersByTime(600 * 1000); await flush(); expect(session.grant).toBe(renewed); expect(sessionsRequests()).toHaveLength(0); @@ -1430,15 +1431,15 @@ describe('grant (signed session credential)', () => { it('waits while the messenger is open, then ends once it closes (at most an hour)', async () => { let open = true; - GleapFrameManager.getInstance.mockImplementation(() => ({ sendMessage: jest.fn(), sendSessionUpdate: jest.fn(), isOpened: () => open })); + GleapFrameManager.getInstance.mockImplementation(() => ({ sendMessage: vi.fn(), sendSessionUpdate: vi.fn(), isOpened: () => open })); const session = signedIn(600); session.lastIdentify = null; MockXhr.instances = []; - jest.advanceTimersByTime(600 * 1000 + 30 * 60 * 1000); + vi.advanceTimersByTime(600 * 1000 + 30 * 60 * 1000); await flush(); expect(sessionsRequests()).toHaveLength(0); open = false; - jest.advanceTimersByTime(60 * 1000); + vi.advanceTimersByTime(60 * 1000); await flush(); expect(sessionsRequests()).toHaveLength(1); answerUnsigned(sessionsRequests()[0]); @@ -1446,14 +1447,14 @@ describe('grant (signed session credential)', () => { }); it('the messenger left open: the session still ends an hour after the expiry', async () => { - GleapFrameManager.getInstance.mockImplementation(() => ({ sendMessage: jest.fn(), sendSessionUpdate: jest.fn(), isOpened: () => true })); + GleapFrameManager.getInstance.mockImplementation(() => ({ sendMessage: vi.fn(), sendSessionUpdate: vi.fn(), isOpened: () => true })); const session = signedIn(600); session.lastIdentify = null; MockXhr.instances = []; - jest.advanceTimersByTime(600 * 1000 + 59 * 60 * 1000); + vi.advanceTimersByTime(600 * 1000 + 59 * 60 * 1000); await flush(); expect(sessionsRequests()).toHaveLength(0); - jest.advanceTimersByTime(2 * 60 * 1000); + vi.advanceTimersByTime(2 * 60 * 1000); await flush(); expect(sessionsRequests()).toHaveLength(1); }); @@ -1501,13 +1502,13 @@ describe('grant (signed session credential)', () => { it('a provider token that already expired counts as a failure (30 s pause)', async () => { const session = readySession(); - const provider = jest.fn(() => jwtOf({ userId: 'user-1', exp: inSeconds(0) })); + const provider = vi.fn(() => jwtOf({ userId: 'user-1', exp: inSeconds(0) })); session.setUserJwtProvider(provider); await expect(session.requestUserJwt()).resolves.toBe(null); expect(warn).toHaveBeenCalledWith(expect.stringContaining('expired token')); await expect(session.requestUserJwt()).resolves.toBe(null); expect(provider).toHaveBeenCalledTimes(1); - jest.advanceTimersByTime(30 * 1000); + vi.advanceTimersByTime(30 * 1000); await session.requestUserJwt(); expect(provider).toHaveBeenCalledTimes(2); }); diff --git a/src/GleapShadowSelector.test.js b/src/GleapShadowSelector.test.js index 7ee556e5..580fd039 100644 --- a/src/GleapShadowSelector.test.js +++ b/src/GleapShadowSelector.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, expect } from 'vitest'; import { querySelectorSafe, querySelectorAllSafe, matchesSelectorSafe } from './GleapSafeSelector'; import { buildStableSelector, withShadowHosts } from './GleapTourSelector'; diff --git a/src/GleapStreamedEvent.test.js b/src/GleapStreamedEvent.test.js index 24614de5..14cf9f0d 100644 --- a/src/GleapStreamedEvent.test.js +++ b/src/GleapStreamedEvent.test.js @@ -1,21 +1,22 @@ +import { describe, it, test, expect, vi, beforeEach, afterEach } from 'vitest'; import Gleap, { GleapMetaDataManager, GleapNotificationManager, GleapSession } from './Gleap'; import GleapStreamedEvent from './GleapStreamedEvent'; // Stub the barrel so the real GleapStreamedEvent loads without a DOM or the // SDK_VERSION Webpack global. -jest.mock('./Gleap', () => ({ +vi.mock('./Gleap', () => ({ __esModule: true, - default: { getInstance: jest.fn() }, - GleapFrameManager: { getInstance: jest.fn(() => ({ isOpened: () => false })) }, - GleapMetaDataManager: { getInstance: jest.fn(() => ({})) }, - GleapAiChatbarManager: { getInstance: jest.fn(() => ({})) }, - GleapNotificationManager: { getInstance: jest.fn() }, - GleapSession: { getInstance: jest.fn(() => ({})) }, - GleapAdminManager: { getInstance: jest.fn(() => ({})) }, - GleapEventManager: { notifyEvent: jest.fn() }, + default: { getInstance: vi.fn() }, + GleapFrameManager: { getInstance: vi.fn(() => ({ isOpened: () => false })) }, + GleapMetaDataManager: { getInstance: vi.fn(() => ({})) }, + GleapAiChatbarManager: { getInstance: vi.fn(() => ({})) }, + GleapNotificationManager: { getInstance: vi.fn() }, + GleapSession: { getInstance: vi.fn(() => ({})) }, + GleapAdminManager: { getInstance: vi.fn(() => ({})) }, + GleapEventManager: { notifyEvent: vi.fn() }, })); -jest.mock('./GleapHelper', () => ({ +vi.mock('./GleapHelper', () => ({ gleapDataParser: (data) => data, })); @@ -23,41 +24,41 @@ describe('startPageListener — notification page-rule re-evaluation (#141052)', let checkPageRulesForUrl; beforeEach(() => { - jest.useFakeTimers(); - checkPageRulesForUrl = jest.fn(); + vi.useFakeTimers(); + checkPageRulesForUrl = vi.fn(); GleapNotificationManager.getInstance.mockReturnValue({ checkPageRulesForUrl }); global.window = { location: { href: 'https://app.example.com/a' } }; }); afterEach(() => { - jest.useRealTimers(); + vi.useRealTimers(); delete global.window; }); test('re-evaluates page rules every tick, even with page tracking disabled', () => { Gleap.getInstance.mockReturnValue({ disablePageTracking: true }); const streamer = new GleapStreamedEvent(); - const logEventSpy = jest.spyOn(streamer, 'logEvent'); + const logEventSpy = vi.spyOn(streamer, 'logEvent'); streamer.startPageListener(); - jest.advanceTimersByTime(1000); + vi.advanceTimersByTime(1000); expect(checkPageRulesForUrl).toHaveBeenCalledWith('https://app.example.com/a'); // disablePageTracking must only suppress pageView streaming, not page rules. expect(logEventSpy).not.toHaveBeenCalled(); global.window.location.href = 'https://app.example.com/b'; - jest.advanceTimersByTime(1000); + vi.advanceTimersByTime(1000); expect(checkPageRulesForUrl).toHaveBeenLastCalledWith('https://app.example.com/b'); }); test('still streams pageView events when page tracking is enabled', () => { Gleap.getInstance.mockReturnValue({ disablePageTracking: false }); const streamer = new GleapStreamedEvent(); - const logEventSpy = jest.spyOn(streamer, 'logEvent'); + const logEventSpy = vi.spyOn(streamer, 'logEvent'); streamer.startPageListener(); - jest.advanceTimersByTime(1000); + vi.advanceTimersByTime(1000); expect(logEventSpy).toHaveBeenCalledWith('pageView', { page: 'https://app.example.com/a' }); expect(checkPageRulesForUrl).toHaveBeenCalledWith('https://app.example.com/a'); @@ -113,14 +114,14 @@ describe('event pings', () => { // Advances the clock and runs a loop tick; true when that tick sent a ping. const tickAfter = (streamer, ms) => { const count = requests.length; - jest.advanceTimersByTime(ms); + vi.advanceTimersByTime(ms); streamer.streamEvents(); return requests.length > count; }; beforeEach(() => { - jest.useFakeTimers(); - jest.setSystemTime(new Date('2026-01-01T00:00:00Z')); + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-01-01T00:00:00Z')); requests = []; global.XMLHttpRequest = FakeXHR; global.SDK_VERSION = 'test'; @@ -128,17 +129,17 @@ describe('event pings', () => { ready: true, session: { gleapId: 'id', gleapHash: 'hash' }, apiUrl: 'https://api.test', - injectSession: jest.fn(), + injectSession: vi.fn(), }; GleapSession.getInstance.mockReturnValue(sessionInstance); GleapMetaDataManager.getInstance.mockReturnValue({ getSessionDuration: () => 1 }); // No jitter: every delay is exactly its base value. - jest.spyOn(Math, 'random').mockReturnValue(0.5); + vi.spyOn(Math, 'random').mockReturnValue(0.5); }); afterEach(() => { - jest.useRealTimers(); - jest.restoreAllMocks(); + vi.useRealTimers(); + vi.restoreAllMocks(); delete global.XMLHttpRequest; delete global.SDK_VERSION; }); @@ -169,7 +170,7 @@ describe('event pings', () => { expect(tickAfter(streamer, 29999)).toBe(false); // Timed out: aborted, counted as a failure, the events stay and go again after the backoff. - jest.advanceTimersByTime(1); + vi.advanceTimersByTime(1); expect(requests[0].aborted).toBe(true); expect(names(streamer.streamedEventArray)).toEqual(['a', 'b']); expect(tickAfter(streamer, 2999)).toBe(false); @@ -363,12 +364,12 @@ describe('WebSocket reconnects', () => { // Advances the clock; true when a new socket was opened in that time. const reconnectsAfter = (ms) => { const count = sockets.length; - jest.advanceTimersByTime(ms); + vi.advanceTimersByTime(ms); return sockets.length > count; }; beforeEach(() => { - jest.useFakeTimers(); + vi.useFakeTimers(); sockets = []; online = true; global.WebSocket = FakeWebSocket; @@ -379,12 +380,12 @@ describe('WebSocket reconnects', () => { sessionInstance = { session: { gleapId: 'id', gleapHash: 'hash' }, sdkKey: 'key', wsApiUrl: 'wss://ws.test' }; GleapSession.getInstance.mockReturnValue(sessionInstance); // No jitter: every delay is exactly its base value. - jest.spyOn(Math, 'random').mockReturnValue(0.5); + vi.spyOn(Math, 'random').mockReturnValue(0.5); }); afterEach(() => { - jest.useRealTimers(); - jest.restoreAllMocks(); + vi.useRealTimers(); + vi.restoreAllMocks(); delete global.WebSocket; delete global.SDK_VERSION; delete global.window; @@ -418,14 +419,14 @@ describe('WebSocket reconnects', () => { // Accepted, then closed before 10 s: still backs off. latest().open(); - jest.advanceTimersByTime(9999); + vi.advanceTimersByTime(9999); latest().drop(); expect(reconnectsAfter(1999)).toBe(false); expect(reconnectsAfter(1)).toBe(true); // Open for 10 s: 1 s again. latest().open(); - jest.advanceTimersByTime(10000); + vi.advanceTimersByTime(10000); latest().drop(); expect(reconnectsAfter(999)).toBe(false); expect(reconnectsAfter(1)).toBe(true); @@ -446,10 +447,10 @@ describe('WebSocket reconnects', () => { latest().drop(); streamer.handleClose({}); // Just the reconnect: no second one and no ping interval of the dropped socket. - expect(jest.getTimerCount()).toBe(1); + expect(vi.getTimerCount()).toBe(1); - jest.spyOn(streamer, 'trackInitialEvents').mockImplementation(() => {}); - jest.spyOn(streamer, 'runEventStreamLoop').mockImplementation(() => {}); + vi.spyOn(streamer, 'trackInitialEvents').mockImplementation(() => {}); + vi.spyOn(streamer, 'runEventStreamLoop').mockImplementation(() => {}); sessionInstance.session = { gleapId: 'id2', gleapHash: 'hash2' }; streamer.restart(); expect(sockets).toHaveLength(2); @@ -482,7 +483,7 @@ describe('WebSocket reconnects', () => { // A drop while offline schedules nothing. online = false; latest().drop(); - expect(jest.getTimerCount()).toBe(0); + expect(vi.getTimerCount()).toBe(0); // Back online with an open socket: it is kept. online = true; diff --git a/src/GleapSurveyAnalyticsForwarder.test.js b/src/GleapSurveyAnalyticsForwarder.test.js index b426c386..9bd05b67 100644 --- a/src/GleapSurveyAnalyticsForwarder.test.js +++ b/src/GleapSurveyAnalyticsForwarder.test.js @@ -1,13 +1,14 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest'; import { GleapConfigManager } from './Gleap'; import { forwardSurveyAnalyticsEvent, surveyAnalyticsParams } from './GleapSurveyAnalyticsForwarder'; -jest.mock('./Gleap', () => ({ +vi.mock('./Gleap', () => ({ __esModule: true, - default: { getInstance: jest.fn() }, - GleapConfigManager: { getInstance: jest.fn() }, + default: { getInstance: vi.fn() }, + GleapConfigManager: { getInstance: vi.fn() }, })); const setFlowConfig = (flowConfig) => { @@ -31,8 +32,8 @@ describe('GleapSurveyAnalyticsForwarder', () => { beforeEach(() => { setFlowConfig({}); window.dataLayer = []; - window.gtag = jest.fn(); - window.fbq = jest.fn(); + window.gtag = vi.fn(); + window.fbq = vi.fn(); }); afterEach(() => { @@ -96,19 +97,19 @@ describe('GleapSurveyAnalyticsForwarder', () => { test('each sink is optional', () => { delete window.gtag; delete window.fbq; - window.dataLayer = { push: jest.fn() }; // not an array: left alone + window.dataLayer = { push: vi.fn() }; // not an array: left alone expect(() => forwardSurveyAnalyticsEvent('survey-shown', message({ forward: true }))).not.toThrow(); expect(window.dataLayer.push).not.toHaveBeenCalled(); delete window.dataLayer; - window.fbq = jest.fn(); + window.fbq = vi.fn(); forwardSurveyAnalyticsEvent('survey-shown', message({ forward: true })); expect(window.fbq).toHaveBeenCalledTimes(1); expect(window.dataLayer).toBeUndefined(); }); test('a throwing sink does not stop the others', () => { - window.gtag = jest.fn(() => { + window.gtag = vi.fn(() => { throw new Error('gtag broken'); }); expect(forwardSurveyAnalyticsEvent('survey-shown', message({ forward: true }))).toBe(true); diff --git a/src/GleapTabCommunication.test.js b/src/GleapTabCommunication.test.js index 42b77401..6bdc5698 100644 --- a/src/GleapTabCommunication.test.js +++ b/src/GleapTabCommunication.test.js @@ -1,3 +1,4 @@ +import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest'; import { GleapNotificationManager, GleapSession, @@ -8,11 +9,11 @@ import GleapTabCommunication from './GleapTabCommunication'; // Keep the barrel import light (no DOM, no SDK_VERSION Webpack global): only the // managers GleapTabCommunication actually reaches for. -jest.mock('./Gleap', () => ({ - GleapNotificationManager: { getInstance: jest.fn() }, - GleapSession: { getInstance: jest.fn() }, - GleapFeedbackButtonManager: { getInstance: jest.fn() }, - GleapAiChatbarManager: { getInstance: jest.fn() }, +vi.mock('./Gleap', () => ({ + GleapNotificationManager: { getInstance: vi.fn() }, + GleapSession: { getInstance: vi.fn() }, + GleapFeedbackButtonManager: { getInstance: vi.fn() }, + GleapAiChatbarManager: { getInstance: vi.fn() }, })); // Minimal BroadcastChannel stand-in. Node's test env has no BroadcastChannel, so @@ -63,9 +64,9 @@ beforeEach(() => { MockBroadcastChannel.reset(); global.BroadcastChannel = MockBroadcastChannel; - notifStub = { clearAllNotifications: jest.fn(), clearNotificationsForConversation: jest.fn() }; - buttonStub = { updateNotificationBadge: jest.fn() }; - chatbarStub = { hideChatbarNotification: jest.fn() }; + notifStub = { clearAllNotifications: vi.fn(), clearNotificationsForConversation: vi.fn() }; + buttonStub = { updateNotificationBadge: vi.fn() }; + chatbarStub = { hideChatbarNotification: vi.fn() }; sessionStub = { sdkKey: SDK_KEY, session: { gleapId: 'user-1' } }; GleapNotificationManager.getInstance.mockReturnValue(notifStub); @@ -153,7 +154,7 @@ describe('inbound notifications-cleared', () => { test('applying the inbound clear does not post back on the channel (loop guard)', () => { const tc = GleapTabCommunication.getInstance(); tc.start(); - const postSpy = jest.spyOn(tc.channel, 'postMessage'); + const postSpy = vi.spyOn(tc.channel, 'postMessage'); openSiblingTab().postMessage({ type: 'notifications-cleared', gleapId: 'user-1' }); @@ -227,7 +228,7 @@ describe('inbound conversation-notifications-cleared', () => { test('applying the inbound clear does not post back on the channel (loop guard)', () => { const tc = GleapTabCommunication.getInstance(); tc.start(); - const postSpy = jest.spyOn(tc.channel, 'postMessage'); + const postSpy = vi.spyOn(tc.channel, 'postMessage'); openSiblingTab().postMessage({ type: 'conversation-notifications-cleared', @@ -274,7 +275,7 @@ describe('inbound chatbar-notification-cleared', () => { test('applying the inbound dismissal does not post back on the channel (loop guard)', () => { const tc = GleapTabCommunication.getInstance(); tc.start(); - const postSpy = jest.spyOn(tc.channel, 'postMessage'); + const postSpy = vi.spyOn(tc.channel, 'postMessage'); openSiblingTab().postMessage({ type: 'chatbar-notification-cleared', gleapId: 'user-1' }); diff --git a/src/GleapThemeManager.test.js b/src/GleapThemeManager.test.js index 572e380d..9a29224d 100644 --- a/src/GleapThemeManager.test.js +++ b/src/GleapThemeManager.test.js @@ -1,34 +1,35 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest'; -const mockRefreshColorScheme = jest.fn(); -const mockSetStyles = jest.fn(); -const mockSendConfigUpdate = jest.fn(); -const mockChatbarSendConfigUpdate = jest.fn(); +const mockRefreshColorScheme = vi.fn(); +const mockSetStyles = vi.fn(); +const mockSendConfigUpdate = vi.fn(); +const mockChatbarSendConfigUpdate = vi.fn(); const mockChatbar = { comReady: false, _sendConfigUpdate: mockChatbarSendConfigUpdate }; -const mockSendModalData = jest.fn(); +const mockSendModalData = vi.fn(); -jest.mock('./Gleap', () => ({ +vi.mock('./Gleap', () => ({ __esModule: true, default: { setStyles: (...args) => mockSetStyles(...args) }, GleapConfigManager: { getInstance: () => { - // The real config manager is used by the integration tests below. - const RealConfigManager = jest.requireActual('./GleapConfigManager').default; + // The real config manager (the module imported below, not this mock) is used by the integration tests below. + const RealConfigManager = GleapConfigManager; return mockUseRealConfigManager ? RealConfigManager.getInstance() : { refreshColorScheme: mockRefreshColorScheme, rawFlowConfig: mockDashboardConfig }; }, }, GleapFrameManager: { getInstance: () => ({ sendConfigUpdate: mockSendConfigUpdate }) }, - GleapFeedbackButtonManager: { getInstance: () => ({ updateFeedbackButtonState: jest.fn() }) }, - GleapNotificationManager: { getInstance: () => ({ updateContainerStyle: jest.fn() }) }, - GleapReplayRecorder: { getInstance: () => ({ startIfNotRunning: jest.fn(), stop: jest.fn() }) }, + GleapFeedbackButtonManager: { getInstance: () => ({ updateFeedbackButtonState: vi.fn() }) }, + GleapNotificationManager: { getInstance: () => ({ updateContainerStyle: vi.fn() }) }, + GleapReplayRecorder: { getInstance: () => ({ startIfNotRunning: vi.fn(), stop: vi.fn() }) }, GleapNetworkIntercepter: { - getInstance: () => ({ start: jest.fn(), setLoadAllResources: jest.fn(), setFilters: jest.fn(), setBlacklist: jest.fn() }), + getInstance: () => ({ start: vi.fn(), setLoadAllResources: vi.fn(), setFilters: vi.fn(), setBlacklist: vi.fn() }), }, - GleapTranslationManager: { getInstance: () => ({ updateRTLSupport: jest.fn(), getActiveLanguage: () => 'en' }) }, + GleapTranslationManager: { getInstance: () => ({ updateRTLSupport: vi.fn(), getActiveLanguage: () => 'en' }) }, GleapAiChatbarManager: { getInstance: () => mockChatbar }, GleapModalManager: { getInstance: () => ({ sendModalData: mockSendModalData }) }, GleapSession: { getInstance: () => ({}) }, @@ -57,10 +58,10 @@ const resetDocument = () => { }; beforeEach(() => { - jest.useFakeTimers(); + vi.useFakeTimers(); prefersDark = false; mediaListeners = []; - window.matchMedia = jest.fn(() => ({ + window.matchMedia = vi.fn(() => ({ get matches() { return prefersDark; }, @@ -78,11 +79,11 @@ beforeEach(() => { mockUseRealConfigManager = false; mockDashboardConfig = { colorScheme: 'light' }; mockChatbar.comReady = false; - jest.clearAllMocks(); + vi.clearAllMocks(); }); afterEach(() => { - jest.useRealTimers(); + vi.useRealTimers(); }); describe('parseColor', () => { @@ -484,7 +485,7 @@ describe('auto color scheme', () => { // Unrelated mutations don't trigger a refresh. document.body.style.overflow = 'hidden'; await Promise.resolve(); - jest.runAllTimers(); + vi.runAllTimers(); expect(mockRefreshColorScheme).toHaveBeenCalledTimes(2); document.documentElement.classList.remove('dark'); @@ -505,7 +506,7 @@ describe('auto color scheme', () => { mockRefreshColorScheme.mockClear(); document.documentElement.classList.add('dark'); await Promise.resolve(); - jest.runAllTimers(); + vi.runAllTimers(); expect(mockRefreshColorScheme).not.toHaveBeenCalled(); }); @@ -538,7 +539,7 @@ describe('GleapConfigManager integration', () => { const configManager = GleapConfigManager.getInstance(); configManager.applyConfig(serverConfig()); expect(configManager.getFlowConfig().backgroundColor).toBe('#FFFFFF'); - jest.clearAllMocks(); + vi.clearAllMocks(); // Still light (light host), so nothing is re-sent. GleapThemeManager.getInstance().setColorScheme('auto'); @@ -575,7 +576,7 @@ describe('GleapConfigManager integration', () => { const configManager = GleapConfigManager.getInstance(); configManager.applyConfig({ flowConfig: { ...serverConfig().flowConfig, colorScheme: 'auto', darkBackgroundColor: '#101828' } }); expect(configManager.getFlowConfig().backgroundColor).toBe('#FFFFFF'); - jest.clearAllMocks(); + vi.clearAllMocks(); document.documentElement.classList.add('dark'); await Promise.resolve(); @@ -599,7 +600,7 @@ describe('GleapConfigManager integration', () => { expect(configManager.getFlowConfig()).toBe(flowConfig); const checklist = document.createElement('gleap-checklist'); document.body.appendChild(checklist); - jest.clearAllMocks(); + vi.clearAllMocks(); GleapThemeManager.getInstance().setColorScheme('dark'); expect(configManager.getFlowConfig()).toBe(flowConfig); @@ -618,7 +619,7 @@ describe('GleapConfigManager integration', () => { configManager.applyConfig({ flowConfig }); const checklist = document.createElement('gleap-checklist'); document.body.appendChild(checklist); - jest.clearAllMocks(); + vi.clearAllMocks(); GleapThemeManager.getInstance().setColorScheme('dark', { darkBackgroundColor: '#000000' }); expect(configManager.getFlowConfig()).toBe(flowConfig); @@ -651,9 +652,9 @@ describe('GleapConfigManager integration', () => { const checklist = document.createElement('gleap-checklist'); checklist._hasLoaded = true; checklist.checklistData = { id: 'c1' }; - checklist.renderChecklist = jest.fn(); + checklist.renderChecklist = vi.fn(); document.body.appendChild(checklist); - jest.clearAllMocks(); + vi.clearAllMocks(); GleapThemeManager.getInstance().setColorScheme('dark'); const flowConfig = configManager.getFlowConfig(); @@ -675,7 +676,7 @@ describe('GleapConfigManager integration', () => { configManager.applyConfig({ flowConfig: { colorScheme: 'light', backgroundColor: '#111111', color: '#485BFF', headerColor: '#485BFF', darkBackgroundColor: '#111111' }, }); - jest.clearAllMocks(); + vi.clearAllMocks(); GleapThemeManager.getInstance().setColorScheme('dark'); expect(configManager.getFlowConfig().backgroundColor).toBe('#111111'); @@ -706,7 +707,7 @@ describe('GleapConfigManager integration', () => { darkAurora: { ...aurora, seed: 2 }, }, }); - jest.clearAllMocks(); + vi.clearAllMocks(); GleapThemeManager.getInstance().setColorScheme('dark'); const flowConfig = configManager.getFlowConfig(); diff --git a/src/GleapTooltipManager.test.js b/src/GleapTooltipManager.test.js index 9b6748d8..17ad2dfb 100644 --- a/src/GleapTooltipManager.test.js +++ b/src/GleapTooltipManager.test.js @@ -1,25 +1,26 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, test, expect, vi, beforeEach } from 'vitest'; import GleapTooltipManager from './GleapTooltipManager'; -jest.mock('./Gleap', () => ({ +vi.mock('./Gleap', () => ({ __esModule: true, default: {}, - GleapSession: { getInstance: jest.fn(() => ({})) }, + GleapSession: { getInstance: vi.fn(() => ({})) }, })); -jest.mock('./UI', () => ({ - loadIcon: jest.fn(() => ''), +vi.mock('./UI', () => ({ + loadIcon: vi.fn(() => ''), })); -jest.mock('@floating-ui/dom', () => ({ - autoUpdate: jest.fn(() => jest.fn()), - computePosition: jest.fn(() => Promise.resolve({ x: 0, y: 0, middlewareData: {}, placement: 'right' })), - arrow: jest.fn(), - flip: jest.fn(), - offset: jest.fn(), - shift: jest.fn(), +vi.mock('@floating-ui/dom', () => ({ + autoUpdate: vi.fn(() => vi.fn()), + computePosition: vi.fn(() => Promise.resolve({ x: 0, y: 0, middlewareData: {}, placement: 'right' })), + arrow: vi.fn(), + flip: vi.fn(), + offset: vi.fn(), + shift: vi.fn(), })); const hotspotTooltip = (overrides = {}) => ({ diff --git a/src/GleapTourSelector.test.js b/src/GleapTourSelector.test.js index 28f9a10a..16dfba6f 100644 --- a/src/GleapTourSelector.test.js +++ b/src/GleapTourSelector.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, expect, beforeEach } from 'vitest'; import { UNSTABLE_SELECTOR_PATTERN, buildStableSelector } from './GleapTourSelector'; const resolvesToElement = (selector, element) => { diff --git a/src/GleapTours.test.js b/src/GleapTours.test.js index 81cb417d..c85151bb 100644 --- a/src/GleapTours.test.js +++ b/src/GleapTours.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import GleapTours from './GleapTours'; // jsdom has no layout, so every element reports no client rects. Treat an @@ -20,11 +21,11 @@ describe('GleapTours step target resolution', () => { let onElementNotFound; beforeEach(() => { - jest.useFakeTimers(); - jest.spyOn(Element.prototype, 'getClientRects').mockImplementation(function () { + vi.useFakeTimers(); + vi.spyOn(Element.prototype, 'getClientRects').mockImplementation(function () { return isHiddenInTest(this) ? [] : [{ top: 0, left: 0, width: 40, height: 20 }]; }); - onElementNotFound = jest.fn(() => tour.destroy()); + onElementNotFound = vi.fn(() => tour.destroy()); }); afterEach(() => { @@ -32,9 +33,9 @@ describe('GleapTours step target resolution', () => { tour.destroy(); } tour = null; - jest.runOnlyPendingTimers(); - jest.useRealTimers(); - jest.restoreAllMocks(); + vi.runOnlyPendingTimers(); + vi.useRealTimers(); + vi.restoreAllMocks(); document.body.innerHTML = ''; }); @@ -65,7 +66,7 @@ describe('GleapTours step target resolution', () => { expect(tour.getActiveElement()).toBeUndefined(); expect(document.querySelector('.label').classList.contains('gleap-tour-active-element')).toBe(false); - jest.advanceTimersByTime(5200); + vi.advanceTimersByTime(5200); expect(onElementNotFound).toHaveBeenCalledTimes(1); expect(onElementNotFound.mock.calls[0][0].element).toBe('.menu-item > .label'); @@ -86,12 +87,12 @@ describe('GleapTours step target resolution', () => { document.body.innerHTML = ''; startTour('.menu-item > .label'); - jest.advanceTimersByTime(1000); + vi.advanceTimersByTime(1000); document.querySelector('.label').style.display = ''; - jest.advanceTimersByTime(200); + vi.advanceTimersByTime(200); expect(tour.getActiveElement()).toBe(document.querySelector('.label')); - jest.advanceTimersByTime(5000); + vi.advanceTimersByTime(5000); expect(onElementNotFound).not.toHaveBeenCalled(); }); @@ -99,7 +100,7 @@ describe('GleapTours step target resolution', () => { document.body.innerHTML = ''; startTour('.menu-item > .label'); - jest.advanceTimersByTime(5200); + vi.advanceTimersByTime(5200); expect(onElementNotFound).toHaveBeenCalledTimes(1); }); diff --git a/src/GleapUserJwt.test.js b/src/GleapUserJwt.test.js index 21b01e47..ddb04eee 100644 --- a/src/GleapUserJwt.test.js +++ b/src/GleapUserJwt.test.js @@ -1,3 +1,4 @@ +import { describe, it, expect } from 'vitest'; import { decodeUserJwt, identifyRefusalOf } from './GleapUserJwt'; const b64url = (value) => Buffer.from(value).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); diff --git a/src/ScreenCapture.test.js b/src/ScreenCapture.test.js index c408f8b8..959171e1 100644 --- a/src/ScreenCapture.test.js +++ b/src/ScreenCapture.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, test, expect, vi, beforeEach, afterEach } from 'vitest'; import { startScreenCapture } from './ScreenCapture'; @@ -15,7 +16,7 @@ const fakeAnimation = (target, property = 'opacity') => ({ }); const installRootAnimations = (root, animations) => { - root.getAnimations = jest.fn(() => animations); + root.getAnimations = vi.fn(() => animations); return root.getAnimations; }; @@ -215,7 +216,7 @@ const fakeComputedStyle = (values) => { // A '::before' / '::after' entry in an element's values is the style of that pseudo-element. const stubComputedStyles = (stylesByElement) => { const getComputedStyle = window.getComputedStyle; - jest.spyOn(window, 'getComputedStyle').mockImplementation((element, pseudo) => { + vi.spyOn(window, 'getComputedStyle').mockImplementation((element, pseudo) => { if (!stylesByElement.has(element)) { return getComputedStyle.call(window, element, pseudo); } @@ -255,7 +256,7 @@ describe('startScreenCapture — blocked elements', () => { }); afterEach(() => { - jest.restoreAllMocks(); + vi.restoreAllMocks(); }); // Private: the text, the attributes (the id too), and a nested image, link and field. @@ -465,8 +466,8 @@ describe('startScreenCapture — blocked elements', () => { '
' + ''; const requested = []; - jest.spyOn(XMLHttpRequest.prototype, 'open').mockImplementation((method, url) => requested.push(url)); - jest.spyOn(XMLHttpRequest.prototype, 'send').mockImplementation(function () { + vi.spyOn(XMLHttpRequest.prototype, 'open').mockImplementation((method, url) => requested.push(url)); + vi.spyOn(XMLHttpRequest.prototype, 'send').mockImplementation(function () { this.onerror(); }); @@ -509,7 +510,7 @@ describe('startScreenCapture — blocked elements keep the layout around them', }); afterEach(() => { - jest.restoreAllMocks(); + vi.restoreAllMocks(); delete Range.prototype.getClientRects; }); @@ -724,7 +725,7 @@ describe('startScreenCapture — blocked elements keep the layout around them', describe('baselines', () => { beforeEach(() => { - jest.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({ + vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({ measureText: () => ({ fontBoundingBoxAscent: 14 }), }); }); @@ -844,7 +845,7 @@ describe('startScreenCapture — masked text', () => { }); test("the site's maskTextFn formats masked text, as in replays", async () => { - const maskTextFn = jest.fn((text) => `[${text.length}]`); + const maskTextFn = vi.fn((text) => `[${text.length}]`); document.body.innerHTML = '

Jane Doe

'; const doc = parse((await startScreenCapture(true, { maskTextFn })).html); @@ -952,7 +953,7 @@ describe('startScreenCapture — frames', () => { document.body.innerHTML = ''; document.getElementById('dialog').contentDocument.body.innerHTML = '

Fortschritt

'; const setAttribute = Element.prototype.setAttribute; - const spy = jest.spyOn(HTMLIFrameElement.prototype, 'setAttribute').mockImplementation(function (name, value) { + const spy = vi.spyOn(HTMLIFrameElement.prototype, 'setAttribute').mockImplementation(function (name, value) { if (name === 'srcdoc') { throw new TypeError("This document requires 'TrustedHTML' assignment."); } diff --git a/src/ScreenDrawer.test.js b/src/ScreenDrawer.test.js index 0fde6113..4a8bbdc3 100644 --- a/src/ScreenDrawer.test.js +++ b/src/ScreenDrawer.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import { ScreenDrawer } from './ScreenDrawer'; const setScroll = (x, y) => { diff --git a/vitest.config.mjs b/vitest.config.mjs new file mode 100644 index 00000000..c292a070 --- /dev/null +++ b/vitest.config.mjs @@ -0,0 +1,13 @@ +import { defineConfig } from 'vitest/config'; + +// Unit tests run in node; a test file that needs a DOM says so in its docblock (`@vitest-environment jsdom`). +// The built bundle is tested in a real browser by Playwright (playwright.config.mjs), not here. +export default defineConfig({ + test: { + include: ['src/**/*.test.js', 'tools/**/*.test.mjs'], + // The page URL the tests were written against (Jest's default). Vitest's own default adds port 3000. + environmentOptions: { jsdom: { url: 'http://localhost/' } }, + // Node's own Web Storage (on by default from Node 25) shadows jsdom's localStorage. Workers always run without it. + execArgv: ['--no-experimental-webstorage'], + }, +}); From ead88dedfc7354854a33087a8ee032c8517c083c Mon Sep 17 00:00:00 2001 From: Tobias duelli Date: Wed, 18 Nov 2026 14:40:04 +0100 Subject: [PATCH 3/3] chore(quality): take the core that finds the default branch Copied from Frontend's fix-quality-core-default-branch (b2deefd0d2, draft PR GleapSDK/Frontend#3079), which is not on Frontend's master yet. Co-Authored-By: Claude Opus 5.5 --- tools/quality/changes.mjs | 24 ++++++++++++++++-------- tools/quality/check.mjs | 2 +- tools/quality/core.cases.mjs | 22 ++++++++++++++++++++++ tools/quality/core.sha256 | 2 +- 4 files changed, 40 insertions(+), 10 deletions(-) diff --git a/tools/quality/changes.mjs b/tools/quality/changes.mjs index 0ad05286..a68fccc8 100644 --- a/tools/quality/changes.mjs +++ b/tools/quality/changes.mjs @@ -4,8 +4,6 @@ import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpat import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; -const DEFAULT_BASE = 'origin/master'; - const git = ({ root, args, input, env }) => execFileSync('git', args, { cwd: root, @@ -34,23 +32,33 @@ export const forkPointOf = ({ root, base, head }) => gitText({ root, args: ['mer export const headOf = ({ root }) => gitText({ root, args: ['rev-parse', 'HEAD'] }); -// The closest remote branch this one left. origin/master wins a tie, and a branch that holds this one plus more +// origin/HEAD as the clone recorded it, else origin/main or origin/master, whichever exists. +const defaultBranchOf = ({ root, rows }) => { + try { + return gitText({ root, args: ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'] }); + } catch { + return ['origin/main', 'origin/master'].find((ref) => rows.some((row) => row.startsWith(`${ref} `))); + } +}; + +// The closest remote branch this one left. The default branch wins a tie, and a branch that holds this one plus more // is its child, not its base. A ref at this very commit is this work pushed under another name, unless the commit is -// on origin/master anyway. Costs about 250 ms across 2000 refs, so the answer is kept per commit. +// on the default branch anyway. Costs about 250 ms across 2000 refs, so the answer is kept per commit. const findBase = ({ root, head }) => { const branch = gitText({ root, args: ['branch', '--show-current'] }); const skipped = new Set(['origin/HEAD', 'origin', `origin/${branch}`]); const refs = gitText({ root, args: ['for-each-ref', '--format=%(refname:short) %(ahead-behind:HEAD)', 'refs/remotes/origin'] }); const rows = refs.split('\n').filter(Boolean); - const defaultRow = rows.find((row) => row.startsWith(`${DEFAULT_BASE} `)); + const defaultBase = defaultBranchOf({ root, rows }); + const defaultRow = rows.find((row) => row.startsWith(`${defaultBase} `)); const isAheadOfDefault = !defaultRow || Number(defaultRow.split(' ')[2]) > 0; let best = null; for (const row of rows) { const [ref, ahead, behind] = row.split(' '); - const isChild = Number(ahead) > 0 && Number(behind) === 0 && ref !== DEFAULT_BASE; - const isThisCommit = Number(ahead) === 0 && Number(behind) === 0 && ref !== DEFAULT_BASE; + const isChild = Number(ahead) > 0 && Number(behind) === 0 && ref !== defaultBase; + const isThisCommit = Number(ahead) === 0 && Number(behind) === 0 && ref !== defaultBase; if (skipped.has(ref) || isChild || (isThisCommit && isAheadOfDefault)) continue; - const isBetter = !best || Number(behind) < best.behind || (Number(behind) === best.behind && ref === DEFAULT_BASE); + const isBetter = !best || Number(behind) < best.behind || (Number(behind) === best.behind && ref === defaultBase); if (isBetter) best = { ref, behind: Number(behind) }; } if (!best) throw new Error(`no remote branch to compare ${head.slice(0, 10)} with`); diff --git a/tools/quality/check.mjs b/tools/quality/check.mjs index f3a5177e..26c14439 100644 --- a/tools/quality/check.mjs +++ b/tools/quality/check.mjs @@ -154,7 +154,7 @@ const main = async () => { try { return await runFile(values.file); } catch (error) { - // An edit hook must not stop a session over a missing origin/master or typescript. CI still runs it. + // An edit hook must not stop a session over a missing default branch or typescript. CI still runs it. console.error(`quality check skipped for ${values.file}: ${error.message}`); return 0; } diff --git a/tools/quality/core.cases.mjs b/tools/quality/core.cases.mjs index 528a1da1..57cac109 100644 --- a/tools/quality/core.cases.mjs +++ b/tools/quality/core.cases.mjs @@ -941,6 +941,28 @@ export const defineCoreCases = ({ describe, it, afterAll, config, LIMITS, checkC git(repo, 'update-ref', 'refs/remotes/origin/sibling', 'HEAD'); assert.ok(run(repo).out.includes('origin/master')); }); + // The hooks pass no --base. A branch without commits of its own sits on the default branch, which wins. + it('takes the default branch from origin/HEAD', () => { + const repo = makeRepo(EXISTING); + put(repo, LOGIC, broken(90)); + git(repo, 'commit', '-qam', 'develop moved on'); + git(repo, 'update-ref', 'refs/remotes/origin/develop', 'HEAD'); + git(repo, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/develop'); + const { code, out } = run(repo); + assert.equal(code, 0, out); + assert.ok(out.includes('origin/develop'), out); + }); + it('without origin/HEAD, takes origin/main over an old merged branch', () => { + const repo = makeRepo(EXISTING); + git(repo, 'update-ref', 'refs/remotes/origin/old-fix', 'HEAD'); + git(repo, 'update-ref', '-d', 'refs/remotes/origin/master'); + put(repo, LOGIC, broken(90)); + git(repo, 'commit', '-qam', 'main moved on'); + git(repo, 'update-ref', 'refs/remotes/origin/main', 'HEAD'); + const { code, out } = run(repo); + assert.equal(code, 0, out); + assert.ok(out.includes('origin/main'), out); + }); it('does not write to the index or the object store of the checkout', () => { const repo = makeRepo(EXISTING); put(repo, pathFor('fresh'), moduleOf(1)); diff --git a/tools/quality/core.sha256 b/tools/quality/core.sha256 index 01ab295d..69958074 100644 --- a/tools/quality/core.sha256 +++ b/tools/quality/core.sha256 @@ -1 +1 @@ -6fc118c76ca20471bb6eeac82abf1a7bbbac8fe65e091b0d8d09a6b33bff38dc +08c8424e02fba5e2718a721ad3f00c0374650ec713b995c724ac0e686bd63029