From 2616c02e1529f974cb322958566f22a9d1d08528 Mon Sep 17 00:00:00 2001 From: Henric Trotzig Date: Wed, 18 Dec 2024 11:47:53 +0100 Subject: [PATCH] Remove the need for `context` in `beforeAll` While debugging things for a customer, we found that `beforeAll` doesn't give us a context that we can use. While running the local tests, I found that I could initialize the takeDOMSnapshot function lazily when needed. This will simplify setup for users of this library. I'm making this a "soft" breaking change by generating a warning log if you pass a context to happoPlaywright.init. This way people can discover the simplification without much disruption. --- index.js | 28 ++++++++++++++++++++++++++-- tests/app.spec.js | 6 +++--- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/index.js b/index.js index 2de357e..e545da1 100644 --- a/index.js +++ b/index.js @@ -3,9 +3,31 @@ const pathToBrowserBuild = require.resolve('happo-e2e/browser.build.js'); const controller = new Controller(); +async function lazyLoadBrowserBundle(page) { + if ( + await page.evaluate(() => typeof window.happoTakeDOMSnapshot === 'undefined') + ) { + await page.addScriptTag({ path: pathToBrowserBuild }); + + // Add timeout check for happoTakeDOMSnapshot + try { + await page.waitForFunction( + () => typeof window.happoTakeDOMSnapshot !== 'undefined', + { timeout: 10000 }, + ); + } catch (error) { + throw new Error('Timed out waiting for happoTakeDOMSnapshot to be defined'); + } + } +} + module.exports = { - async init(contextOrPage) { - await contextOrPage.addInitScript({ path: pathToBrowserBuild }); + async init(pageOrContext) { + if (pageOrContext) { + console.warn( + '[HAPPO] You no longer need to pass a page or context to happoPlaywright.init()', + ); + } await controller.init(); }, @@ -30,6 +52,8 @@ module.exports = { ); } + await lazyLoadBrowserBundle(page); + const elementHandle = handleOrLocator.elementHandle ? await handleOrLocator.elementHandle() : handleOrLocator; diff --git a/tests/app.spec.js b/tests/app.spec.js index c37477e..82e195c 100644 --- a/tests/app.spec.js +++ b/tests/app.spec.js @@ -1,11 +1,11 @@ const { test, expect } = require('@playwright/test'); const happoPlaywright = require('../'); -test.beforeEach(async ({ context }) => { - await happoPlaywright.init(context); +test.beforeAll(async () => { + await happoPlaywright.init(); }); -test.afterEach(async () => { +test.afterAll(async () => { await happoPlaywright.finish(); });