{"id":15825173,"url":"https://github.com/karlhorky/playwright-tricks","last_synced_at":"2025-08-02T00:32:09.186Z","repository":{"id":234179884,"uuid":"773917380","full_name":"karlhorky/playwright-tricks","owner":"karlhorky","description":"A collection of helpful tricks for Playwright tests","archived":false,"fork":false,"pushed_at":"2024-07-17T17:09:48.000Z","size":12,"stargazers_count":6,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2024-10-25T23:10:45.261Z","etag":null,"topics":["playwright","testing"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/karlhorky.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-03-18T16:15:05.000Z","updated_at":"2024-10-12T14:58:20.000Z","dependencies_parsed_at":"2024-04-18T12:13:50.794Z","dependency_job_id":"0d016c97-c8ea-482d-878a-99b0d42ad81e","html_url":"https://github.com/karlhorky/playwright-tricks","commit_stats":{"total_commits":6,"total_committers":1,"mean_commits":6.0,"dds":0.0,"last_synced_commit":"a0b09c60fff48e71303883037f71743bd3b61b56"},"previous_names":["karlhorky/playwright-tricks"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/karlhorky%2Fplaywright-tricks","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/karlhorky%2Fplaywright-tricks/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/karlhorky%2Fplaywright-tricks/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/karlhorky%2Fplaywright-tricks/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/karlhorky","download_url":"https://codeload.github.com/karlhorky/playwright-tricks/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":228419545,"owners_count":17916768,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["playwright","testing"],"created_at":"2024-10-05T09:05:18.289Z","updated_at":"2024-12-06T05:47:50.416Z","avatar_url":"https://github.com/karlhorky.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Playwright Tricks\n\nA collection of helpful tricks for [Playwright](https://playwright.dev/) tests\n\n## Interoperable Text Snapshots\n\nPlaywright does not add a newline at the end of files created with [non-image snapshots](https://playwright.dev/docs/test-snapshots#non-image-snapshots) - the text snapshots created with `expect().toMatchSnapshot()` - as discussed in [`microsoft/playwright#33416`](https://github.com/microsoft/playwright/issues/33416).\n\nThis means that the following code will create a file `snapshot.txt` with the content `abc`, without any newline at the end:\n\n```ts\nimport { test, expect } from '@playwright/test';\n\ntest('example test', () =\u003e {\n  expect('abc').toMatchSnapshot('snapshot.txt');\n});\n```\n\nSnapshot files without newlines at the ends are problematic because commonly-used software like the GitHub \"Edit in Place\" feature and other common editor configurations will silently add a newline in the edge case of editing a snapshot file, which will cause the snapshot test to fail in a confusing way.\n\nAlso, [POSIX and *nix tools assume newlines at the end of files](https://stackoverflow.com/questions/729692/why-should-text-files-end-with-a-newline), so Playwright text snapshots will not play nice with those.\n\nUnless the Playwright team reverses [their \"working as intended\" decision](https://github.com/microsoft/playwright/issues/33416#issuecomment-2455936144) and adds a fix to make text snapshots interoperable Create interoperable, this needs to be worked around.\n\n[The current workaround](https://github.com/microsoft/playwright/issues/33416#issuecomment-2456363012) to create robust text snapshots with Playwright is to manually adding a newline at the end of the string passed to `expect()`:\n\n```ts\nimport { test, expect } from '@playwright/test';\n\ntest('example test', () =\u003e {\n  expect(\n    'abc' +\n      // Make Playwright snapshot file interoperable\n      // - https://github.com/microsoft/playwright/issues/33416#issuecomment-2456363012\n      '\\n',\n  ).toMatchSnapshot('snapshot.txt');\n});\n```\n\n## Load All Lazy Images\n\nScroll to all visible lazy-loaded images and wait for [successful loading of image](#test-image-loading):\n\n```ts\nconst lazyImages = await page.locator('img[loading=\"lazy\"]:visible').all();\n\nfor (const lazyImage of lazyImages) {\n  await lazyImage.scrollIntoViewIfNeeded();\n  await expect(lazyImage).not.toHaveJSProperty('naturalWidth', 0);\n}\n```\n\nBe aware, [using `.all()` can be problematic if new images are being added, removed, shown or hidden while the test code is running](https://github.com/microsoft/playwright/issues/31737).\n\nOne workaround for this is to assert the length of the `.all()` array (if you know it) to wait for it to stabilize:\n\n```ts\nconst lazyImagesLocator = page.locator('img[loading=\"lazy\"]:visible');\n\n// Assert on length to wait for image visibility to stabilize\n// after client-side JavaScript hides some images\n// https://github.com/microsoft/playwright/issues/31737#issuecomment-2233775909\nawait expect(lazyImagesLocator).toHaveCount(13);\n\nconst lazyImages = await lazyImagesLocator.all();\n\nfor (const lazyImage of lazyImages) {\n  await lazyImage.scrollIntoViewIfNeeded();\n  await expect(lazyImage).not.toHaveJSProperty('naturalWidth', 0);\n}\n```\n\n## Screenshot Comparison Tests of PDFs\n\nPlaywright does not (as of June 2024) have support for [visual comparison testing](https://playwright.dev/docs/test-snapshots) with PDFs.\n\nThere are [many issues asking for this feature](https://github.com/microsoft/playwright/issues?q=is%3Aissue+sort%3Aupdated-desc+pdfs+is%3Aclosed), but the current position of the Playwright team is that [PDF.js should be used instead](https://github.com/microsoft/playwright/issues/19253#issuecomment-1338955863), to render the PDF to a canvas.\n\nIt's not clear how the Playwright team suggests to do this, but one way is to navigate to `about:blank`, use [`page.setContent()`](https://playwright.dev/docs/api/class-page#page-set-content) to add a PDF.js viewer to the page, which accepts a URL, and then use [`expect(page).toHaveScreenshot()`](https://playwright.dev/docs/api/class-pageassertions#page-assertions-to-have-screenshot-2):\n\n```ts\n// HTML template string no-op for VS Code highlighting / formatting\nfunction html(strings: TemplateStringsArray, ...values: unknown[]) {\n  return strings.reduce((result, string, i) =\u003e {\n    return result + string + (values[i] ?? '');\n  }, '');\n}\n\ntest('PDF has screenshot', async ({ page }) =\u003e {\n  // Go to page without Content-Security-Policy header, to avoid CSP\n  // prevention of script loading from https://mozilla.github.io\n  await page.goto('about:blank');\n\n  await page.setContent(html`\n    \u003c!doctype html\u003e\n    \u003chtml\u003e\n      \u003chead\u003e\n        \u003cmeta charset=\"UTF-8\" /\u003e\n      \u003c/head\u003e\n      \u003cbody\u003e\n        \u003ccanvas\u003e\u003c/canvas\u003e\n        \u003cscript src=\"https://mozilla.github.io/pdf.js/build/pdf.mjs\" type=\"module\"\u003e\u003c/script\u003e\n        \u003cscript type=\"module\"\u003e\n          pdfjsLib.GlobalWorkerOptions.workerSrc =\n            'https://mozilla.github.io/pdf.js/build/pdf.worker.mjs';\n\n          try {\n            const pdf = await pdfjsLib.getDocument(\n               'https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/examples/learning/helloworld.pdf',\n            ).promise;\n\n            const page = await pdf.getPage(1);\n            const viewport = page.getViewport({ scale: 1.5 });\n\n            const canvas = document.querySelector('canvas');\n            canvas.height = viewport.height;\n            canvas.width = viewport.width;\n\n            await page.render({\n              canvasContext: canvas.getContext('2d'),\n              viewport,\n            }).promise;\n          } catch (error) {\n            console.error('Error loading PDF:', error);\n          }\n        \u003c/script\u003e\n      \u003c/body\u003e\n    \u003c/html\u003e\n  `);\n\n  await page.waitForTimeout(1000);\n\n  await expect(page).toHaveScreenshot({ fullPage: true });\n});\n```\n\n## Test Image Loading\n\nTest that `\u003cimg\u003e` elements have a `src` attribute that is reachable and responds with image data:\n\n```ts\nconst img = page.locator('img');\nawait expect(img).not.toHaveJSProperty('naturalWidth', 0);\n```\n\nSource: https://github.com/microsoft/playwright/issues/6046#issuecomment-1803609118\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkarlhorky%2Fplaywright-tricks","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkarlhorky%2Fplaywright-tricks","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkarlhorky%2Fplaywright-tricks/lists"}