Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Refactor Playwright tests (#3614)
Olga Bulat88e5103c0de9
diff --git a/frontend/test/playwright/e2e/attribution.spec.ts b/frontend/test/playwright/e2e/attribution.spec.tsindex c6a4e50f2..b12eaab75 100644--- a/frontend/test/playwright/e2e/attribution.spec.ts+++ b/frontend/test/playwright/e2e/attribution.spec.ts@@ -1,76 +1,75 @@import { test, expect } from "@playwright/test"-import { turnOnAnalytics } from "~~/test/playwright/utils/navigation"+import { preparePageForTests } from "~~/test/playwright/utils/navigation"+import {+ collectAnalyticsEvents,+ expectEventPayloadToMatch,+} from "~~/test/playwright/utils/analytics"test.describe.configure({ mode: "parallel" })-test.beforeEach(async ({ context }) => {- await context.grantPermissions(["clipboard-read", "clipboard-write"])-})--test("can copy rich text attribution", async ({ page }) => {- await page.goto("image/e9d97a98-621b-4ec2-bf70-f47a74380452")- await page.click('[aria-controls="panel-rich"]')- await page.click('[id="copyattr-rich"]')- const clippedText = await page.evaluate(async () => {- return navigator.clipboard.readText()+test.describe("attribution", () => {+ test.beforeEach(async ({ context, page }) => {+ await preparePageForTests(page, "xl", { features: { analytics: "on" } })+ await context.grantPermissions(["clipboard-read", "clipboard-write"])})- // The Clipboard API returns a plain-text-ified version of the rich text.- expect(clippedText).toContain('"bubbles in honey" by mutednarayan')-})-test("can copy HTML attribution", async ({ page }) => {- await page.goto("image/e9d97a98-621b-4ec2-bf70-f47a74380452")- await page.click('[aria-controls="panel-html"]')- await page.click('[id="copyattr-html"]')- const clippedText = await page.evaluate(async () => {- return navigator.clipboard.readText()- })- const snippets = [- '<p class="attribution">',- ">bubbles in honey</a>",- ">mutednarayan</a>",- ]- snippets.forEach((snippet) => {- expect(clippedText).toContain(snippet)+ test("can copy rich text attribution", async ({ page }) => {+ await page.goto("image/e9d97a98-621b-4ec2-bf70-f47a74380452")+ await page.click('[aria-controls="panel-rich"]')+ await page.click('[id="copyattr-rich"]')+ const clippedText = await page.evaluate(async () => {+ return navigator.clipboard.readText()+ })+ // The Clipboard API returns a plain-text-ified version of the rich text.+ expect(clippedText).toContain('"bubbles in honey" by mutednarayan')})-})-test("can copy plain text attribution", async ({ page }) => {- await page.goto("image/e9d97a98-621b-4ec2-bf70-f47a74380452")- await page.click('[aria-controls="panel-plain"]')- await page.click('[id="copyattr-plain"]')- const clippedText = await page.evaluate(async () => {- return navigator.clipboard.readText()+ test("can copy HTML attribution", async ({ page }) => {+ await page.goto("image/e9d97a98-621b-4ec2-bf70-f47a74380452")+ await page.click('[aria-controls="panel-html"]')+ await page.click('[id="copyattr-html"]')+ const clippedText = await page.evaluate(async () => {+ return navigator.clipboard.readText()+ })+ const snippets = [+ '<p class="attribution">',+ ">bubbles in honey</a>",+ ">mutednarayan</a>",+ ]+ snippets.forEach((snippet) => {+ expect(clippedText).toContain(snippet)+ })})- // Only the plain-text license contains the "To view" bit.- expect(clippedText).toContain("To view a copy of this license")-})-test("sends analytics event on copy", async ({ page }) => {- let copyAttributionEventData: {- id: string- format: string- mediaType: string- } = { id: "", format: "", mediaType: "" }- page.on("request", (req) => {- if (req.method() === "POST") {- const requestData = req.postDataJSON()- if (requestData?.n == "COPY_ATTRIBUTION") {- copyAttributionEventData = JSON.parse(requestData?.p)- }- }+ test("can copy plain text attribution", async ({ page }) => {+ await page.goto("image/e9d97a98-621b-4ec2-bf70-f47a74380452")+ await page.click('[aria-controls="panel-plain"]')+ await page.click('[id="copyattr-plain"]')+ const clippedText = await page.evaluate(async () => {+ return navigator.clipboard.readText()+ })+ // Only the plain-text license contains the "To view" bit.+ expect(clippedText).toContain("To view a copy of this license")})- const mediaType = "image"- const id = "e9d97a98-621b-4ec2-bf70-f47a74380452"- const format = "rich"- await turnOnAnalytics(page)+ test("sends analytics event on copy", async ({ page }) => {+ const analyticsEvents = collectAnalyticsEvents(page.context())- await page.goto(`${mediaType}/${id}?ff_analytics=on`)- await page.click(`[id="copyattr-${format}"]`)+ const mediaType = "image"+ const id = "e9d97a98-621b-4ec2-bf70-f47a74380452"+ const format = "rich"- expect(copyAttributionEventData.id).toEqual(id)- expect(copyAttributionEventData.format).toEqual(format)- expect(copyAttributionEventData.mediaType).toEqual(mediaType)+ await page.goto(`${mediaType}/${id}?ff_analytics=on`)+ await page.click(`[id="copyattr-${format}"]`)++ const copyAttributionEvent = analyticsEvents.find(+ (event) => event.n === "COPY_ATTRIBUTION"+ )+ expectEventPayloadToMatch(copyAttributionEvent, {+ id,+ format,+ mediaType,+ })+ })})diff --git a/frontend/test/playwright/e2e/collections.spec.ts b/frontend/test/playwright/e2e/collections.spec.tsindex 9b12c4676..e2c604a1b 100644--- a/frontend/test/playwright/e2e/collections.spec.ts+++ b/frontend/test/playwright/e2e/collections.spec.ts@@ -1,55 +1,64 @@import { test, expect } from "@playwright/test"-import { setCookies, t } from "~~/test/playwright/utils/navigation"+import { preparePageForTests, t } from "~~/test/playwright/utils/navigation"test.describe.configure({ mode: "parallel" })-test.beforeEach(async ({ context, page }) => {- await setCookies(context, {- features: { additional_search_views: "on", analytics: "off" },+test.describe("collections", () => {+ test.beforeEach(async ({ page }) => {+ await preparePageForTests(page, "xl", {+ features: {+ additional_search_views: "on",+ },+ })+ await page.goto("/image/f9384235-b72e-4f1e-9b05-e1b116262a29?q=cat")})- await page.goto("/image/f9384235-b72e-4f1e-9b05-e1b116262a29?q=cat")-})-test("can open tags collection page from image page", async ({ page }) => {- // Using the href because there are multiple links with the same text.- await page.click('[href*="/tag/cat"]')- await expect(- page.getByRole("button", { name: t("browsePage.load") })- ).toBeEnabled()+ test("can open tags collection page from image page", async ({ page }) => {+ // Using the href because there are multiple links with the same text.+ await page.click('[href*="/tag/cat"]')- await expect(page.getByRole("heading", { name: /cat/i })).toBeVisible()- expect(await page.locator("figure").count()).toEqual(20)- expect(page.url()).toMatch(/image\/tag\/cat/)-})-test("can open source collection page from image page", async ({ page }) => {- const sourcePattern = /flickr/i+ await expect(+ page.getByRole("button", { name: t("browsePage.load") })+ ).toBeEnabled()- await page.getByRole("link", { name: sourcePattern }).first().click()+ await expect(+ page.getByRole("heading", { level: 1, name: /cat/i })+ ).toBeVisible()+ expect(await page.locator("figure").count()).toEqual(20)+ expect(page.url()).toMatch(/image\/tag\/cat/)+ })+ test("can open source collection page from image page", async ({ page }) => {+ const sourcePattern = /flickr/i- await expect(- page.getByRole("button", { name: t("browsePage.load") })- ).toBeEnabled()+ await page.getByRole("link", { name: sourcePattern }).first().click()- await expect(page.getByRole("heading", { name: sourcePattern })).toBeVisible()+ await expect(+ page.getByRole("button", { name: t("browsePage.load") })+ ).toBeEnabled()- expect(await page.locator("figure").count()).toEqual(20)+ await expect(+ page.getByRole("heading", { name: sourcePattern })+ ).toBeVisible()- expect(page.url()).toMatch(/image\/source\/flickr\/$/)-})-test("can open creator collection page from image page", async ({ page }) => {- const creatorPattern = /strogoscope/i- await page.getByRole("link", { name: creatorPattern }).first().click()+ expect(await page.locator("figure").count()).toEqual(20)- await expect(- page.getByRole("button", { name: t("browsePage.load") })- ).toBeEnabled()+ expect(page.url()).toMatch(/image\/source\/flickr\/$/)+ })+ test("can open creator collection page from image page", async ({ page }) => {+ const creatorPattern = /strogoscope/i+ await page.getByRole("link", { name: creatorPattern }).first().click()++ await expect(+ page.getByRole("button", { name: t("browsePage.load") })+ ).toBeEnabled()- await expect(- page.getByRole("heading", { name: creatorPattern })- ).toBeVisible()+ await expect(+ page.getByRole("heading", { level: 1, name: creatorPattern })+ ).toBeVisible()- expect(await page.locator("figure").count()).toEqual(20)+ expect(await page.locator("figure").count()).toEqual(20)- expect(page.url()).toMatch(/image\/source\/flickr\/creator\/strogoscope\//)+ expect(page.url()).toMatch(/image\/source\/flickr\/creator\/strogoscope\//)+ })})diff --git a/frontend/test/playwright/e2e/external-sources.spec.ts b/frontend/test/playwright/e2e/external-sources.spec.tsindex 11c0557de..51f669d0a 100644--- a/frontend/test/playwright/e2e/external-sources.spec.ts+++ b/frontend/test/playwright/e2e/external-sources.spec.ts@@ -2,8 +2,8 @@ import { test } from "@playwright/test"import {goToSearchTerm,+ preparePageForTests,t,- turnOnAnalytics,} from "~~/test/playwright/utils/navigation"import {@@ -11,58 +11,64 @@ import {expectEventPayloadToMatch,} from "~~/test/playwright/utils/analytics"-test("sends VIEW_EXTERNAL_SOURCES analytics events", async ({- page,- context,-}) => {- await turnOnAnalytics(page)- const events = collectAnalyticsEvents(context)+test.describe("analytics", () => {+ test.beforeEach(async ({ page }) => {+ await preparePageForTests(page, "xl", { features: { analytics: "on" } })+ })++ test("sends VIEW_EXTERNAL_SOURCES analytics events", async ({+ page,+ context,+ }) => {+ const events = collectAnalyticsEvents(context)- await goToSearchTerm(page, "cat", { searchType: "image", mode: "SSR" })+ await goToSearchTerm(page, "cat", { searchType: "image", mode: "SSR" })- await page- .getByRole("button", { name: t("externalSources.form.supportedTitle") })- .click()- await page.getByRole("button", { name: /close/i }).click()+ await page+ .getByRole("button", { name: t("externalSources.form.supportedTitle") })+ .click()+ await page.getByRole("button", { name: /close/i }).click()- const viewEvent = events.find((event) => event.n === "VIEW_EXTERNAL_SOURCES")+ const viewEvent = events.find(+ (event) => event.n === "VIEW_EXTERNAL_SOURCES"+ )- expectEventPayloadToMatch(viewEvent, {- searchType: "image",- query: "cat",- resultPage: 1,+ expectEventPayloadToMatch(viewEvent, {+ searchType: "image",+ query: "cat",+ resultPage: 1,+ })})-})-test("sends SELECT_EXTERNAL_SOURCE analytics events", async ({- page,- context,-}) => {- await turnOnAnalytics(page)- const pagePromise = page.context().waitForEvent("page")+ test("sends SELECT_EXTERNAL_SOURCE analytics events", async ({+ page,+ context,+ }) => {+ const pagePromise = page.context().waitForEvent("page")- const events = collectAnalyticsEvents(context)+ const events = collectAnalyticsEvents(context)- await goToSearchTerm(page, "cat", { searchType: "image", mode: "SSR" })+ await goToSearchTerm(page, "cat", { searchType: "image", mode: "SSR" })- await page- .getByRole("button", {- name: new RegExp(t("externalSources.form.supportedTitleSm"), "i"),- })- .click()- await page.getByRole("link", { name: "Centre for Ageing Better" }).click()+ await page+ .getByRole("button", {+ name: new RegExp(t("externalSources.form.supportedTitleSm"), "i"),+ })+ .click()+ await page.getByRole("link", { name: "Centre for Ageing Better" }).click()- const newPage = await pagePromise- await newPage.close()+ const newPage = await pagePromise+ await newPage.close()- const selectEvent = events.find(- (event) => event.n === "SELECT_EXTERNAL_SOURCE"- )+ const selectEvent = events.find(+ (event) => event.n === "SELECT_EXTERNAL_SOURCE"+ )- expectEventPayloadToMatch(selectEvent, {- name: "Centre For Ageing Better",- mediaType: "image",- query: "cat",- component: "VExternalSourceList",+ expectEventPayloadToMatch(selectEvent, {+ name: "Centre For Ageing Better",+ mediaType: "image",+ query: "cat",+ component: "VExternalSourceList",+ })})})diff --git a/frontend/test/playwright/e2e/filters-sidebar-keyboard.spec.ts b/frontend/test/playwright/e2e/filters-sidebar-keyboard.spec.tsindex bb203c64d..1315c89e3 100644--- a/frontend/test/playwright/e2e/filters-sidebar-keyboard.spec.ts+++ b/frontend/test/playwright/e2e/filters-sidebar-keyboard.spec.ts@@ -4,7 +4,7 @@ import {LanguageDirection,languageDirections,pathWithDir,- setBreakpointCookie,+ preparePageForTests,t,} from "~~/test/playwright/utils/navigation"@@ -32,7 +32,7 @@ test.describe.configure({ mode: "parallel" })for (const dir of languageDirections) {test.describe(`search header keyboard accessibility test in ${dir}`, () => {test.beforeEach(async ({ page }) => {- await setBreakpointCookie(page, "lg")+ await preparePageForTests(page, "lg", { dismissFilter: false })/*** To simplify finding the last focusable element in the filters sidebar,* we use the image search page. The last element on the all media searchdiff --git a/frontend/test/playwright/e2e/filters.spec.ts b/frontend/test/playwright/e2e/filters.spec.tsindex e5c781d32..327c46670 100644--- a/frontend/test/playwright/e2e/filters.spec.ts+++ b/frontend/test/playwright/e2e/filters.spec.ts@@ -5,7 +5,7 @@ import {goToSearchTerm,isPageDesktop,filters,- dismissAllBannersUsingCookies,+ preparePageForTests,} from "~~/test/playwright/utils/navigation"import { mockProviderApis } from "~~/test/playwright/utils/route"@@ -44,10 +44,10 @@ const FILTER_COUNTS = {[IMAGE]: 73,}-breakpoints.describeMobileAndDesktop(() => {+breakpoints.describeMobileAndDesktop(({ breakpoint }) => {test.beforeEach(async ({ context, page }) => {await mockProviderApis(context)- await dismissAllBannersUsingCookies(page)+ await preparePageForTests(page, breakpoint)})for (const searchType of supportedSearchTypes) {test(`correct total number of filters is displayed for ${searchType}`, async ({diff --git a/frontend/test/playwright/e2e/global-audio.spec.ts b/frontend/test/playwright/e2e/global-audio.spec.tsindex 404d9a659..84cd844b0 100644--- a/frontend/test/playwright/e2e/global-audio.spec.ts+++ b/frontend/test/playwright/e2e/global-audio.spec.ts@@ -1,11 +1,18 @@import { expect, test } from "@playwright/test"-import { sleep, t } from "~~/test/playwright/utils/navigation"+import {+ preparePageForTests,+ sleep,+ t,+} from "~~/test/playwright/utils/navigation"import breakpoints from "~~/test/playwright/utils/breakpoints"import audio from "~~/test/playwright/utils/audio"test.describe("Global Audio", () => {breakpoints.describeXs(() => {+ test.beforeEach(async ({ page }) => {+ await preparePageForTests(page, "xs")+ })test("track continues playing when navigating from search to details page", async ({page,}) => {diff --git a/frontend/test/playwright/e2e/header-internal.spec.ts b/frontend/test/playwright/e2e/header-internal.spec.tsindex bc6ad91ba..c6c3f4583 100644--- a/frontend/test/playwright/e2e/header-internal.spec.ts+++ b/frontend/test/playwright/e2e/header-internal.spec.ts@@ -5,7 +5,6 @@ import {LanguageDirection,preparePageForTests,scrollToBottom,- setBreakpointCookie,t,} from "~~/test/playwright/utils/navigation"import breakpoints from "~~/test/playwright/utils/breakpoints"@@ -110,7 +109,7 @@ test.describe("Header internal", () => {test("can open and close the popover on sm breakpoint", async ({page,}) => {- await setBreakpointCookie(page, "sm")+ await preparePageForTests(page, "sm")await page.goto("/about")await clickMenuButton(page)expect(await isPagesPopoverOpen(page)).toBe(true)diff --git a/frontend/test/playwright/e2e/image-detail.spec.ts b/frontend/test/playwright/e2e/image-detail.spec.tsindex a21864540..6d11c5313 100644--- a/frontend/test/playwright/e2e/image-detail.spec.ts+++ b/frontend/test/playwright/e2e/image-detail.spec.ts@@ -1,11 +1,7 @@import { test, expect, Page } from "@playwright/test"import { mockProviderApis } from "~~/test/playwright/utils/route"-import {- setCookies,- t,- turnOnAnalytics,-} from "~~/test/playwright/utils/navigation"+import { preparePageForTests, t } from "~~/test/playwright/utils/navigation"import {collectAnalyticsEvents,expectEventPayloadToMatch,@@ -30,7 +26,7 @@ test.beforeEach(async ({ context }) => {})test("shows the author and title of the image", async ({ page }) => {- await setCookies(page.context(), {+ await preparePageForTests(page, "xl", {features: { additional_search_views: "off" },})await goToCustomImagePage(page)@@ -72,11 +68,13 @@ test("shows the 404 error page when no id", async ({ page }) => {})test.describe("analytics", () => {+ test.beforeEach(async ({ page }) => {+ await preparePageForTests(page, "xl", { features: { analytics: "on" } })+ })test("sends GET_MEDIA event on CTA button click", async ({context,page,}) => {- await turnOnAnalytics(page)const analyticsEvents = collectAnalyticsEvents(context)await goToCustomImagePage(page)@@ -98,7 +96,6 @@ test.describe("analytics", () => {context,page,}) => {- await turnOnAnalytics(page)const analyticsEvents = collectAnalyticsEvents(context)await goToCustomImagePage(page)diff --git a/frontend/test/playwright/e2e/skip-to-content.spec.ts b/frontend/test/playwright/e2e/skip-to-content.spec.tsindex f1e1cb3d2..b8a1948b2 100644--- a/frontend/test/playwright/e2e/skip-to-content.spec.ts+++ b/frontend/test/playwright/e2e/skip-to-content.spec.ts@@ -2,10 +2,7 @@ import { expect, test } from "@playwright/test"import breakpoints from "~~/test/playwright/utils/breakpoints"-import {- dismissBannersUsingCookies,- setBreakpointCookie,-} from "~~/test/playwright/utils/navigation"+import { preparePageForTests } from "~~/test/playwright/utils/navigation"import { keycodes } from "~/constants/key-codes"import { skipToContentTargetId } from "~/constants/window"@@ -29,8 +26,9 @@ const pages = [for (const pageUrl of pages) {breakpoints.describeMobileAndDesktop(async ({ breakpoint }) => {test(`can skip to content on ${pageUrl}`, async ({ page }) => {- await dismissBannersUsingCookies(page)- await setBreakpointCookie(page, breakpoint)+ await preparePageForTests(page, breakpoint, {+ features: { fetch_sensitive: "off" },+ })await page.goto(pageUrl)diff --git a/frontend/test/playwright/e2e/translation-banner.spec.ts b/frontend/test/playwright/e2e/translation-banner.spec.tsindex 9b0879bed..e635b903a 100644--- a/frontend/test/playwright/e2e/translation-banner.spec.ts+++ b/frontend/test/playwright/e2e/translation-banner.spec.ts@@ -1,6 +1,6 @@import { test, expect } from "@playwright/test"-import { dismissBannersUsingCookies } from "~~/test/playwright/utils/navigation"+import { preparePageForTests } from "~~/test/playwright/utils/navigation"const russianSearchPath = "/ru/search?q=dog"@@ -29,7 +29,7 @@ test.describe("translation banner", () => {test("Banner is not shown if dismissed state is saved in a cookie", async ({page,}) => {- await dismissBannersUsingCookies(page)+ await preparePageForTests(page, "xl")await page.goto(russianSearchPath)await expect(page.locator('[data-testid="banner-translation"]')).toBeHidden(diff --git a/frontend/test/playwright/utils/navigation.ts b/frontend/test/playwright/utils/navigation.tsindex 3c63402a1..ddc76bb20 100644--- a/frontend/test/playwright/utils/navigation.ts+++ b/frontend/test/playwright/utils/navigation.ts@@ -225,42 +225,6 @@ export const currentContentType = async (page: Page) => {return currentContentType}-export const dismissAllBannersUsingCookies = async (page: Page) => {- const uiDismissedBanners = [- ...["ru", "en", "ar", "es"].map((lang) => `translation-${lang}`),- "analytics",- ]- await setCookies(page.context(), { uiDismissedBanners })-}--/**- * Dismisses the translation banner if it is visible. It does not wait for the banner to become visible,- * so the page should finish rendering before calling `dismissTranslationBanner`.- */-export const dismissTranslationBanner = async (page: Page) => {- await dismissAllBannersUsingCookies(page)- const bannerCloseButton = page.locator(- '[data-testid="banner-translation"] button'- )- if (await bannerCloseButton.isVisible()) {- await bannerCloseButton.click()- }-}--/**- * Dismisses the analytics banner if it is visible. It does not wait for the banner to become visible,- * so the page should finish rendering before calling `dismissAnalyticsBanner`.- */-export const dismissAnalyticsBanner = async (page: Page) => {- await dismissAllBannersUsingCookies(page)- const bannerCloseButton = page.locator(- '[data-testid="banner-analytics"] button'- )- if (await bannerCloseButton.isVisible()) {- await bannerCloseButton.click()- }-}-export const selectHomepageSearchType = async (page: Page,searchType: SupportedSearchType,@@ -274,18 +238,32 @@ export const selectHomepageSearchType = async (.click()}-export const dismissBannersUsingCookies = async (page: Page) => {- await dismissAnalyticsBanner(page)- await dismissTranslationBanner(page)-}-+const ALL_TEST_BANNERS = [+ ...["ru", "en", "ar", "es"].map((lang) => `translation-${lang}`),+ "analytics",+]export const preparePageForTests = async (page: Page,- breakpoint: Breakpoint+ breakpoint: Breakpoint,+ options: Partial<{+ features: Record<string, "on" | "off">+ dismissBanners: boolean+ dismissFilter: boolean+ }> = {}) => {- await dismissAllBannersUsingCookies(page)- await closeFiltersUsingCookies(page)- await setBreakpointCookie(page, breakpoint)+ const { features = {}, dismissBanners = true, dismissFilter = true } = options+ const featuresCookie: Record<string, "on" | "off"> = {}+ if (options.features) {+ for (const [feature, status] of Object.entries(features)) {+ featuresCookie[feature] = status+ }+ }+ await setCookies(page.context(), {+ features: featuresCookie,+ uiDismissedBanners: dismissBanners ? ALL_TEST_BANNERS : [],+ uiIsFilterDismissed: dismissFilter ?? false,+ uiBreakpoint: breakpoint,+ })}export const goToSearchTerm = async (@@ -303,7 +281,6 @@ export const goToSearchTerm = async (const mode = options.mode ?? "SSR"const query = options.query ? `&${options.query}` : ""- await dismissAllBannersUsingCookies(page)if (mode === "SSR") {const path = `${searchPath(searchType)}?q=${term}${query}`await page.goto(pathWithDir(path, dir))@@ -426,31 +403,44 @@ export const setCookies = async (context: BrowserContext,cookies: CookieMap) => {- await context.addCookies(- Object.entries(cookies).map(([name, value]) => ({+ const existingCookies = await context.cookies()+ const cookiesToSet = Object.entries(cookies).map(([name, value]) => {+ let existingValue = existingCookies.find((c) => c.name === name)?.value++ // If cookie was URI encoded, it starts with %7B%22 `{"` or %5B%22 `["`+ if (+ existingValue &&+ (existingValue.includes("%7B%22") || existingValue.includes("%5B%22"))+ ) {+ existingValue = decodeURIComponent(existingValue)+ }+ let newCookieValue = ""+ if (existingValue) {+ if (Array.isArray(value)) {+ newCookieValue = JSON.stringify(+ Array.from(new Set([...JSON.parse(existingValue), ...value]))+ )+ } else if (typeof value === "string") {+ newCookieValue = value+ } else if (typeof value === "object") {+ newCookieValue = JSON.stringify({+ ...JSON.parse(existingValue),+ ...value,+ })+ } else if (typeof value === "boolean") {+ newCookieValue = String(value)+ }+ } else {+ newCookieValue = typeof value === "string" ? value : JSON.stringify(value)+ }++ return {name,- value: typeof value === "string" ? value : JSON.stringify(value),+ value: newCookieValue,domain: "localhost",path: "/",maxAge: 60 * 5,- }))- )-}--export const closeFiltersUsingCookies = async (page: Page) => {- await setCookies(page.context(), { uiIsFilterDismissed: true })-}--export const setBreakpointCookie = async (page: Page, breakpoint: string) => {- await setCookies(page.context(), { uiBreakpoint: breakpoint })-}--export const turnOnAnalytics = async (page: Page) => {- await page.goto("/preferences")- const analyticsCheckbox = page.getByLabel(- "Record custom events and page views."- )- if (!(await analyticsCheckbox.isChecked())) {- await analyticsCheckbox.click()- }+ }+ })+ await context.addCookies(cookiesToSet)}diff --git a/frontend/test/playwright/visual-regression/components/content-report-form.spec.ts b/frontend/test/playwright/visual-regression/components/content-report-form.spec.tsindex d2481b2f1..7215b3ef8 100644--- a/frontend/test/playwright/visual-regression/components/content-report-form.spec.ts+++ b/frontend/test/playwright/visual-regression/components/content-report-form.spec.ts@@ -1,6 +1,6 @@import { Page, test } from "@playwright/test"-import { t } from "~~/test/playwright/utils/navigation"+import { preparePageForTests, t } from "~~/test/playwright/utils/navigation"import breakpoints from "~~/test/playwright/utils/breakpoints"const imageUrl = "/image/feb91b13-422d-46fa-8ef4-cbf1e6ddee9b"@@ -19,6 +19,7 @@ const getReportForm = (page: Page) => {breakpoints.describeMd(({ expectSnapshot }) => {test("unfocused close button", async ({ page }) => {+ await preparePageForTests(page, "md")await page.goto(imageUrl)await getReportButton(page).click()@@ -33,6 +34,7 @@ test.describe("content report form", () => {breakpoints.describeMd(({ expectSnapshot }) => {test("focused close button", async ({ page }) => {+ await preparePageForTests(page, "md")await page.goto(imageUrl)await getReportButton(page).click()diff --git a/frontend/test/playwright/visual-regression/components/external-sources-section.spec.ts b/frontend/test/playwright/visual-regression/components/external-sources-section.spec.tsindex ad07a95d7..741f22bce 100644--- a/frontend/test/playwright/visual-regression/components/external-sources-section.spec.ts+++ b/frontend/test/playwright/visual-regression/components/external-sources-section.spec.ts@@ -3,6 +3,7 @@ import { test } from "@playwright/test"import {goToSearchTerm,languageDirections,+ preparePageForTests,t,} from "~~/test/playwright/utils/navigation"@@ -14,34 +15,38 @@ test.describe.configure({ mode: "parallel" })for (const dir of languageDirections) {for (const mediaType of supportedMediaTypes) {- breakpoints.describeMobileAndDesktop(async ({ expectSnapshot }) => {- test(`External ${mediaType} sources popover - ${dir}`, async ({- page,- }) => {- await goToSearchTerm(page, "birds", { searchType: mediaType, dir })-- const externalSourcesButton = page.getByRole("button", {- name: new RegExp(- t("externalSources.form.supportedTitleSm", dir),- "i"- ),+ breakpoints.describeMobileAndDesktop(+ async ({ breakpoint, expectSnapshot }) => {+ test(`external ${mediaType} sources popover - ${dir}`, async ({+ page,+ }) => {+ await preparePageForTests(page, breakpoint)++ await goToSearchTerm(page, "birds", { searchType: mediaType, dir })++ const externalSourcesButton = page.getByRole("button", {+ name: new RegExp(+ t("externalSources.form.supportedTitleSm", dir),+ "i"+ ),+ })++ await page+ .getByRole("contentinfo")+ .getByRole("link", { name: "Openverse" })+ .scrollIntoViewIfNeeded()++ await externalSourcesButton.click()+ await page.mouse.move(0, 0)++ await expectSnapshot(+ `external-${mediaType}-sources-popover-${dir}`,+ page.getByRole("dialog"),+ {},+ { maxDiffPixelRatio: 0.01, maxDiffPixels: undefined }+ )})-- await page- .getByRole("contentinfo")- .getByRole("link", { name: "Openverse" })- .scrollIntoViewIfNeeded()-- await externalSourcesButton.click()- await page.mouse.move(0, 0)-- await expectSnapshot(- `external-${mediaType}-sources-popover-${dir}`,- page.getByRole("dialog"),- {},- { maxDiffPixelRatio: 0.01 }- )- })- })+ }+ )}}diff --git a/frontend/test/playwright/visual-regression/components/filters.spec.ts b/frontend/test/playwright/visual-regression/components/filters.spec.tsindex ebc0a0454..1a4e2d9f6 100644--- a/frontend/test/playwright/visual-regression/components/filters.spec.ts+++ b/frontend/test/playwright/visual-regression/components/filters.spec.ts@@ -1,11 +1,10 @@import { test } from "@playwright/test"import {- dismissAllBannersUsingCookies,filters,languageDirections,pathWithDir,- setBreakpointCookie,+ preparePageForTests,} from "~~/test/playwright/utils/navigation"import breakpoints from "~~/test/playwright/utils/breakpoints"@@ -21,8 +20,7 @@ for (const dir of languageDirections) {({ breakpoint, expectSnapshot }) => {const isDesktop = breakpoint === "lg"test.beforeEach(async ({ page }) => {- await setBreakpointCookie(page, breakpoint)- await dismissAllBannersUsingCookies(page)+ await preparePageForTests(page, breakpoint)await page.goto(pathWithDir("/search/?q=birds", dir))await filters.open(page, dir)})diff --git a/frontend/test/playwright/visual-regression/components/global-audio-player.spec.ts b/frontend/test/playwright/visual-regression/components/global-audio-player.spec.tsindex 211c86a85..92f8cc1ab 100644--- a/frontend/test/playwright/visual-regression/components/global-audio-player.spec.ts+++ b/frontend/test/playwright/visual-regression/components/global-audio-player.spec.ts@@ -1,11 +1,10 @@import { test } from "@playwright/test"import {- dismissTranslationBanner,- dismissAnalyticsBanner,languageDirections,pathWithDir,t,+ preparePageForTests,} from "~~/test/playwright/utils/navigation"import breakpoints from "~~/test/playwright/utils/breakpoints"import audio from "~~/test/playwright/utils/audio"@@ -15,8 +14,7 @@ for (const dir of languageDirections) {test(`Global audio player on the search page - ${dir}`, async ({page,}) => {- await dismissTranslationBanner(page)- await dismissAnalyticsBanner(page)+ await preparePageForTests(page, "xs")await page.goto(pathWithDir("/search/audio/?q=honey&length=shortest", dir))diff --git a/frontend/test/playwright/visual-regression/components/header.spec.ts b/frontend/test/playwright/visual-regression/components/header.spec.tsindex ffbec5f75..7ff3ae034 100644--- a/frontend/test/playwright/visual-regression/components/header.spec.ts+++ b/frontend/test/playwright/visual-regression/components/header.spec.ts@@ -8,8 +8,8 @@ import {filters,goToSearchTerm,languageDirections,+ preparePageForTests,scrollToBottom,- setBreakpointCookie,sleep,} from "~~/test/playwright/utils/navigation"@@ -21,7 +21,7 @@ for (const dir of languageDirections) {test.describe(`header-${dir}`, () => {breakpoints.describeEvery(({ breakpoint, expectSnapshot }) => {test.beforeEach(async ({ page }) => {- await setBreakpointCookie(page, breakpoint)+ await preparePageForTests(page, breakpoint, { dismissFilter: false })await goToSearchTerm(page, "birds", { dir })})diff --git a/frontend/test/playwright/visual-regression/pages/homepage.spec.ts b/frontend/test/playwright/visual-regression/pages/homepage.spec.tsindex 49ba95aae..0064b41d5 100644--- a/frontend/test/playwright/visual-regression/pages/homepage.spec.ts+++ b/frontend/test/playwright/visual-regression/pages/homepage.spec.ts@@ -3,10 +3,10 @@ import { test, Page } from "@playwright/test"import breakpoints from "~~/test/playwright/utils/breakpoints"import { hideInputCursors } from "~~/test/playwright/utils/page"import {- dismissTranslationBanner,- dismissAnalyticsBanner,languageDirections,pathWithDir,+ preparePageForTests,+ setCookies,} from "~~/test/playwright/utils/navigation"test.describe.configure({ mode: "parallel" })@@ -25,24 +25,24 @@ const cleanImageCarousel = async (page: Page) => {}for (const dir of languageDirections) {- test.describe(`${dir} homepage snapshots`, () => {- const path = pathWithDir("/?ff_additional_search_types=off", dir)- test.beforeEach(async ({ page }) => {- await page.goto(path)- await dismissTranslationBanner(page)- await dismissAnalyticsBanner(page)- await cleanImageCarousel(page)- await page.mouse.move(0, 0)- })+ const path = pathWithDir("/", dir)++ breakpoints.describeEvery(({ breakpoint, expectSnapshot }) => {+ test.describe(`${dir} homepage`, () => {+ test.beforeEach(async ({ page }) => {+ await preparePageForTests(page, breakpoint, {+ features: { additional_search_types: "off" },+ })+ await page.goto(path)+ await cleanImageCarousel(page)+ await page.mouse.move(0, 0)+ })- breakpoints.describeEvery(({ expectSnapshot }) =>test(`${dir} full page`, async ({ page }) => {await expectSnapshot(`index-${dir}`, page)})- )- test.describe("search input", () => {- breakpoints.describeEvery(({ expectSnapshot }) => {+ test.describe("search input", () => {test("unfocused", async ({ page }) => {await expectSnapshot(`unfocused-search-${dir}`,@@ -68,7 +68,11 @@ for (const dir of languageDirections) {test("content switcher with external sources open", async ({page,}) => {- await page.goto(pathWithDir("/?ff_additional_search_types=on", dir))+ await setCookies(page.context(), {+ features: { additional_search_types: "on" },+ })++ await page.goto(path)await cleanImageCarousel(page)await page.locator("#search-type-button").click()diff --git a/frontend/test/playwright/visual-regression/pages/pages-single-result.spec.ts b/frontend/test/playwright/visual-regression/pages/pages-single-result.spec.tsindex 9b01828e5..be24e026a 100644--- a/frontend/test/playwright/visual-regression/pages/pages-single-result.spec.ts+++ b/frontend/test/playwright/visual-regression/pages/pages-single-result.spec.ts@@ -7,7 +7,6 @@ import {openFirstResult,pathWithDir,preparePageForTests,- setCookies,} from "~~/test/playwright/utils/navigation"import { supportedMediaTypes } from "~/constants/media"@@ -21,10 +20,10 @@ for (const isOn of [true, false]) {test(`${mediaType} ${dir} single-result page snapshots from search results, additional search views: ${isOn}`, async ({page,}) => {- await setCookies(page.context(), {+ await preparePageForTests(page, breakpoint, {features: { additional_search_views: isOn ? "on" : "off" },})- await preparePageForTests(page, breakpoint)+await page.route("**", (route) => {const url = route.request().url()// For audio, use the generated image instead of requesting thediff --git a/frontend/test/playwright/visual-regression/pages/pages.spec.ts b/frontend/test/playwright/visual-regression/pages/pages.spec.tsindex 258252c01..627f64706 100644--- a/frontend/test/playwright/visual-regression/pages/pages.spec.ts+++ b/frontend/test/playwright/visual-regression/pages/pages.spec.ts@@ -2,7 +2,6 @@ import { expect, test } from "@playwright/test"import breakpoints from "~~/test/playwright/utils/breakpoints"import {- dismissBannersUsingCookies,languageDirections,pathWithDir,preparePageForTests,@@ -40,7 +39,7 @@ for (const contentPage of contentPages) {test.describe("Layout color is set correctly", () => {breakpoints.describeLg(() => {test.beforeEach(async ({ page }) => {- await dismissBannersUsingCookies(page)+ await preparePageForTests(page, "lg", { dismissFilter: false })})test("Change language on homepage and search", async ({ page }) => {diff --git a/frontend/test/playwright/visual-regression/pages/search-with-banners.spec.ts b/frontend/test/playwright/visual-regression/pages/search-with-banners.spec.tsindex 8a83bff59..7e0c6bccf 100644--- a/frontend/test/playwright/visual-regression/pages/search-with-banners.spec.ts+++ b/frontend/test/playwright/visual-regression/pages/search-with-banners.spec.ts@@ -1,13 +1,16 @@import { test } from "@playwright/test"import breakpoints from "~~/test/playwright/utils/breakpoints"-import { setBreakpointCookie } from "~~/test/playwright/utils/navigation"+import { preparePageForTests } from "~~/test/playwright/utils/navigation"test.describe.configure({ mode: "parallel" })breakpoints.describeEvery(({ breakpoint, expectSnapshot }) => {test.beforeEach(async ({ page }) => {- await setBreakpointCookie(page, breakpoint)+ await preparePageForTests(page, breakpoint, {+ dismissBanners: false,+ dismissFilter: false,+ })await page.goto("/ru/search/?q=birds&referrer=creativecommons.org")})