Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Add local visual regression infrastructure (#1153)

sarayourfriend5396d7272f22
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index bf3ca5a5a..4930d74b9 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -61,8 +61,8 @@ jobs:
- name: Run unit tests
run: pnpm ci:unit-test
- e2e:
- name: E2E tests
+ playwright:
+ name: Playwright tests
runs-on: ubuntu-latest
steps:
@@ -70,8 +70,14 @@ jobs:
- uses: ./.github/actions/setup-node-env
- - name: Run E2E
- run: PW_USER=root ./bin/playwright.sh e2e
+ - name: Run playwright tests
+ run: pnpm test:playwright
+
+ - uses: actions/upload-artifact@v3
+ if: ${{ failure() }}
+ with:
+ name: test-results
+ path: test-results
storybook:
name: Check Storybook build
diff --git a/README.md b/README.md
index 9182d3360..3cb82598b 100644
--- a/README.md
+++ b/README.md
@@ -18,6 +18,8 @@ The frontend app is built using [Vue.js](https://vuejs.org/) and [Nuxt.js](https
## Local Development
+**Note for Windows users:** Please use [WSL](https://docs.microsoft.com/en-us/windows/wsl/install) for developing on the Openverse frontend. Several scripts, primarily support scripts, rely on a general \*nix type environment. Maintaining parity for cross platform scripts proved complicated without significant duplication. If you run into issues with running the Openverse frontend in WSL please let us know by opening an issue or [joining us on Slack](https://make.wordpress.org/chat/) in the `#openverse` room and ask for help.
+
We use [Volta](https://volta.sh/) to manage our local environment tools. Please install it using the instructions on their website.
Once you have volta installed, manually install `pnpm` using volta. [Volta does not currently officially support `pnpm`](https://github.com/volta-cli/volta/issues/737) so this is a stop gap solution until that support is implemented:
diff --git a/TESTING_GUIDELINES.md b/TESTING_GUIDELINES.md
index 93e47d5ae..a355d528a 100644
--- a/TESTING_GUIDELINES.md
+++ b/TESTING_GUIDELINES.md
@@ -68,66 +68,12 @@ The Openverse frontend is a Nuxt SSR application. This means the initial Vue pag
Please note that these are non-expert and non-exhaustive recommendations. Spend time reading the [WAI-ARIA spec](https://www.w3.org/TR/wai-aria/) and other web accessibility materials. Even just knowing about specific roles and interactions that exist and are meant to be developed in consistent ways is a good first step to learning what to look out for when testing.
-## Running the tests
+# Automated tests
-Openverse uses [Vue Testing Library](https://testing-library.com/docs/vue-testing-library/intro/) for unit testing, and [Playwright](https://playwright.dev) for End-to-End (e2e) testing.
+Openverse uses [Vue Testing Library](https://testing-library.com/docs/vue-testing-library/intro/) for unit testing with [Jest](https://jestjs.io/docs/), and [Playwright](https://playwright.dev) for end-to-end and visual-regression testing.
There are also legacy unit tests written in [Vue Test Utils](https://vue-test-utils.vuejs.org/) but those are slated to be re-written using testing library.
-### End-to-end tests
+### Playwright tests
-Our end-to-end test suite runs inside a Playwright docker container in order to prevent cross-platform browser differences from creating flaky test behavior.
-
-Having docker and docker-compose is a pre-requisite to running the end-to-end tests locally. Please follow [the relevant instructions for your operating system for how to install docker and docker-compose](https://docs.docker.com/get-docker/). If you're on Windows 10 Home Edition, please note that you'll need to [install and run docker inside WSL2](https://www.freecodecamp.org/news/how-to-run-docker-on-windows-10-home-edition/).
-
-If it's not possible for you to run docker locally, don't fret! Our CI will run it on every pull request and another contributor who is able to run the tests locally can help you develop new or update existing tests for your changes.
-
-The Playwright docker container runs everything needed for the end-to-end tests, including the Nuxt server and a [Talkback proxy](https://github.com/ijpiantanida/talkback) for the API.
-
-To run the end-to-end tests, after having installed docker, run the following:
-
-```bash
-pnpm test:e2e
-```
-
-If you've added new tests or updated existing ones, you may get errors about API responses not being found. To remedy this, you'll need to update the tapes:
-
-```bash
-pnpm test:e2e:update-tapes
-```
-
-If for some reason you find yourself needing to completely recreate the tapes, you may do so using the `test:e2e:recreate-tapes` script. Please use this sparingly as it creates massive diffs in PRs (tens of thousands of lines across over literally hundreds of JSON files). Note that you may be rate-limited by the upstream production API if you do this. There is no official workaround for this at the moment.
-
-Additional debugging may be accomplished in two ways. You may inspect the trace output of failed tests by finding the `trace.zip` for the relevant test in the `test-results` folder. Traces are only saved for failed tests. You can use the [Playwright Trace Viewer](https://playwright.dev/docs/trace-viewer) to inspect these (or open the zip yourself and poke around the files on your own).
-
-Additionally, you can run run the tests in debug mode. This will run the tests with a headed browser as opposed to a headless (invisible) one and allow you to watch the test happen in real time. It's not possible for a headed browser to run inside the docker container, however, so be aware that when debugging the environment will be slightly different. For example, if you're on any OS other than Linux, the browser you're running will have small differences in how it renders the page compared to the docker container.
-
-To run the debug tests:
-
-```bash
-pnpm test:e2e:debug
-```
-
-Note that this still runs the talkback proxy and the Nuxt server for you. If you'd like to avoid this, simply run the Nuxt server before you run the `test:e2e:debug` script and Playwright will automatically prefer your previously running Nuxt server.
-
-<aside>
-For some reason the following two tests are consistently flaky when updating tapes but appear to be stable when running the e2e tapes with pre-existing tapes.
-
-```
-search-types.spec.js:102:3 › Can open All content page client-side
-search-types.spec.js:102:3 › Can open Images page client-side
-```
-
-Don't be alarmed if you notice this.
-
-</aside>
-
-When writing e2e tests, it can be helpful to use Playwright [codegen](https://playwright.dev/docs/cli#generate-code) to generate the tests by performing actions in the browser:
-
-```
-pnpm run generate-playwright-tests
-```
-
-This will open the app in a new browser window, and record any actions you take in a format that can be used in e2e tests.
-
-Note that this does _not_ run the server for you; you must run the Nuxt server using `pnpm start` or `pnpm dev` separately before running the codegen script.
+Please see the [Playwright test README.md](./test/playwright/README.md) for instructions on running and maintaining the Playwright test suite.
diff --git a/bin/playwright.sh b/bin/playwright.sh
index 5ff8015fe..8ad3502a9 100755
--- a/bin/playwright.sh
+++ b/bin/playwright.sh
@@ -1,7 +1,9 @@
-#! /bin/bash
+#! /usr/bin/env sh
-# todo: find a way to make this portable for Windows users so it can be used for the package.json script
+export USER_ID=${USER_ID:-$(id -u)}
+export PLAYWRIGHT_ARGS=$@
+export PLAYWRIGHT_VERSION=$(pnpm playwright-version --silent)
-export PLAYWRIGHT_VERSION=$(pnpm ls --dev --depth=0 | grep playwright | awk '{print $2}')
-export TEST_TYPE=$1
-docker-compose -f docker-compose.playwright.yml run playwright
+echo Running Playwright v$PLAYWRIGHT_VERSION as $USER_ID with Playwright arguments $PLAYWRIGHT_ARGS
+
+docker-compose -f docker-compose.playwright.yml up --abort-on-container-exit --exit-code-from playwright
diff --git a/docker-compose.playwright.yml b/docker-compose.playwright.yml
index baab6d65c..3df157b08 100644
--- a/docker-compose.playwright.yml
+++ b/docker-compose.playwright.yml
@@ -8,11 +8,10 @@ services:
- PLAYWRIGHT_VERSION=${PLAYWRIGHT_VERSION}
volumes:
- .:/app
- user: ${PW_USER:-pwuser}
+ user: ${USER_ID}
working_dir: /app
- command: |
- sh -c "
- echo 'Please wait while Playwright initializes the web server before running tests. This can take several minutes.';
- pnpm test:${TEST_TYPE}:local;"
+ command: pnpm test:playwright:local -- ${PLAYWRIGHT_ARGS:-}
environment:
+ # This makes the webserver that Playwright runs show the build
+ - DEBUG=pw:webserver
- UPDATE_TAPES=${UPDATE_TAPES:-false}
diff --git a/jest.config.js b/jest.config.js
index 3889773a3..d8021d423 100644
--- a/jest.config.js
+++ b/jest.config.js
@@ -9,6 +9,7 @@ module.exports = {
'^@/(.*)$': '<rootDir>/src/$1',
'^~/(.*.svg)\\?inline$': '<rootDir>/src/$1',
'^~/(.*)$': '<rootDir>/src/$1',
+ '^~~/(.*)$': '<rootDir>/$1',
'^vue$': 'vue/dist/vue.common.js',
'(.*svg)(\\?inline)$': '<rootDir>/test/unit/test-utils/svgTransform.js',
},
@@ -21,7 +22,7 @@ module.exports = {
'jest-transform-stub',
'^.+\\.svg$': '<rootDir>/test/unit/svg-transform.js',
},
- testPathIgnorePatterns: ['/e2e/'],
+ testPathIgnorePatterns: ['/playwright/'],
collectCoverage: true,
coverageDirectory: '<rootDir>/test/unit/coverage',
collectCoverageFrom: [
diff --git a/package.json b/package.json
index 94ac0af19..4d8fa3bac 100644
--- a/package.json
+++ b/package.json
@@ -12,7 +12,7 @@
"author": "sebworks",
"private": true,
"scripts": {
- "dev": "pnpm install && pnpm i18n:create-locales-list && pnpm i18n:update-locales && cross-env nuxt --hostname 0.0.0.0",
+ "dev": "pnpm install && pnpm i18n:create-locales-list && pnpm i18n:update-locales && nuxt --hostname 0.0.0.0",
"dev:secure": "LOCAL_SSL=enabled pnpm dev",
"build": "pnpm i18n:get-translations && nuxt build",
"build-only": "nuxt build",
@@ -21,19 +21,17 @@
"prod": "pnpm build-only && pnpm start",
"storybook": "nuxt storybook",
"test": "jest",
- "test:all": "pnpm test:e2e & jest",
+ "test:all": "pnpm test:playwright & jest",
"test:watch": "jest --collectCoverage=false --watch",
"talkback": "node ./test/proxy.js",
- "pretest:e2e": "pnpm install",
- "test:e2e": "cross-env PLAYWRIGHT_VERSION=1.17.1 TEST_TYPE=e2e docker-compose -f docker-compose.playwright.yml up --abort-on-container-exit --exit-code-from playwright",
- "test:e2e:local": "playwright test -c test/e2e",
- "test:e2e:debug": "cross-env PWDEBUG=1 pnpm test:e2e:local",
- "test:e2e:recreate-tapes": "npm-run-all delete-tapes test:e2e:update-tapes --continue-on-error",
- "test:e2e:update-tapes": "npm-run-all update-tapes fix-tape-permissions --continue-on-error",
+ "playwright-version": "pnpm ls --dev --depth=0 | grep playwright | awk '{print $2}'",
+ "pretest:playwright": "pnpm install",
+ "test:playwright": "./bin/playwright.sh",
+ "test:playwright:local": "playwright test -c test/playwright",
+ "test:playwright:debug": "PWDEBUG=1 pnpm test:playwright:local",
+ "test:playwright:recreate-tapes": "rimraf test/tapes && test:playwright:update-tapes",
+ "test:playwright:update-tapes": "UPDATE_TAPES=true pnpm test:playwright",
"ci:unit-test": "jest --collectCoverage=false",
- "delete-tapes": "rimraf test/tapes",
- "update-tapes": "cross-env UPDATE_TAPES=true pnpm test:e2e",
- "fix-tape-permissions": "docker run -it --rm --mount type=bind,source=$(pwd),target=/app node:alpine chmod -R 0777 /app/test/tapes",
"generate-playwright-test": "playwright codegen localhost:8443/",
"types": "vue-tsc --noEmit",
"lint": "eslint --ext .js,.vue,.ts --ignore-path .gitignore --ignore-path .eslintignore .",
@@ -105,6 +103,7 @@
"@testing-library/vue": "^5.8.2",
"@types/express-useragent": "^1.0.2",
"@types/jest": "^26.0.22",
+ "@types/module-alias": "^2.0.1",
"@types/uuid": "^8.3.4",
"@typescript-eslint/eslint-plugin": "^5.15.0",
"@typescript-eslint/parser": "^5.15.0",
@@ -112,7 +111,6 @@
"@vue/test-utils": "^1.1.3",
"autoprefixer": "^10.4.0",
"babel-jest": "^26.6.3",
- "cross-env": "^7.0.3",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.1.0",
"eslint-import-resolver-custom-alias": "^1.3.0",
@@ -127,6 +125,7 @@
"jest": "^26.6.3",
"jest-transform-stub": "^2.0.0",
"lint-staged": "^11.1.1",
+ "module-alias": "^2.2.2",
"npm-run-all": "^4.1.5",
"pinia": "^2.0.11",
"postcss": "^8.4.5",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b9d0a4a0c..158fe472d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -28,6 +28,7 @@ specifiers:
'@testing-library/vue': ^5.8.2
'@types/express-useragent': ^1.0.2
'@types/jest': ^26.0.22
+ '@types/module-alias': ^2.0.1
'@types/uuid': ^8.3.4
'@typescript-eslint/eslint-plugin': ^5.15.0
'@typescript-eslint/parser': ^5.15.0
@@ -43,7 +44,6 @@ specifiers:
case: ^1.6.3
clipboard: ^2.0.8
core-js: ^3.16.1
- cross-env: ^7.0.3
eslint: ^7.32.0
eslint-config-prettier: ^8.1.0
eslint-import-resolver-custom-alias: ^1.3.0
@@ -70,6 +70,7 @@ specifiers:
lodash.set: ^4.3.2
lodash.sortby: ^4.7.0
lodash.throttle: ^4.1.1
+ module-alias: ^2.2.2
node-html-parser: ^5.1.0
npm-run-all: ^4.1.5
nuxt: ^2.15.4
@@ -151,6 +152,7 @@ devDependencies:
'@testing-library/vue': 5.8.2
'@types/express-useragent': 1.0.2
'@types/jest': 26.0.24
+ '@types/module-alias': 2.0.1
'@types/uuid': 8.3.4
'@typescript-eslint/eslint-plugin': 5.15.0_5400bdff049a1444f15d03ace6195cd2
'@typescript-eslint/parser': [email protected][email protected]
@@ -158,7 +160,6 @@ devDependencies:
'@vue/test-utils': 1.3.0
autoprefixer: [email protected]
babel-jest: 26.6.3
- cross-env: 7.0.3
eslint: 7.32.0
eslint-config-prettier: [email protected]
eslint-import-resolver-custom-alias: [email protected]
@@ -173,6 +174,7 @@ devDependencies:
jest-transform-stub: 2.0.0
lint-staged: 11.2.6
+ module-alias: 2.2.2
npm-run-all: 4.1.5
postcss: 8.4.5
prettier: 2.6.0
@@ -5450,6 +5452,10 @@ packages:
resolution: {integrity: sha512-Klz949h02Gz2uZCMGwDUSDS1YBlTdDDgbWHi+81l29tQALUtvz4rAYi5uoVhE5Lagoq6DeqAUlbrHvW/mXDgdQ==}
dev: true
+ /@types/module-alias/2.0.1:
+ resolution: {integrity: sha512-DN/CCT1HQG6HquBNJdLkvV+4v5l/oEuwOHUPLxI+Eub0NED+lk0YUfba04WGH90EINiUrNgClkNnwGmbICeWMQ==}
+ dev: true
+
/@types/node-fetch/2.6.1:
resolution: {integrity: sha512-oMqjURCaxoSIsHSr1E47QHzbmzNR5rK8McHuNb11BOM9cHcIK3Avy0s/b2JlXHoQGTYS3NsvWzV1M0iK7l0wbA==}
dependencies:
@@ -8083,14 +8089,6 @@ packages:
/create-require/1.1.1:
resolution: {integrity: sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==}
- /cross-env/7.0.3:
- resolution: {integrity: sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==}
- engines: {node: '>=10.14', npm: '>=6', yarn: '>=1'}
- hasBin: true
- dependencies:
- cross-spawn: 7.0.3
- dev: true
-
/cross-spawn/6.0.5:
resolution: {integrity: sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==}
engines: {node: '>=4.8'}
@@ -12863,6 +12861,10 @@ packages:
engines: {node: '>=10'}
hasBin: true
+ /module-alias/2.2.2:
+ resolution: {integrity: sha512-A/78XjoX2EmNvppVWEhM2oGk3x4lLxnkEA4jTbaK97QKSDjkIoOsKQlfylt/d3kKKi596Qy3NP5XrXJ6fZIC9Q==}
+ dev: true
+
/move-concurrently/1.0.1:
resolution: {integrity: sha1-viwAX9oy4LKa8fBdfEszIUxwH5I=}
dependencies:
diff --git a/src/pages/index.vue b/src/pages/index.vue
index 71f1b2a60..a935992f5 100644
--- a/src/pages/index.vue
+++ b/src/pages/index.vue
@@ -80,7 +80,10 @@
</header>
<!-- Image carousel -->
- <div class="flex-grow overflow-hidden w-full lg:w-auto lg:h-full px-6">
+ <div
+ class="flex-grow overflow-hidden w-full lg:w-auto lg:h-full px-6"
+ data-testid="image-carousel"
+ >
<!-- Height is 114.286vh i.e. 100vh * 8/7 (so that 0.75, 1, 1, 0.75 circles are visible) -->
<!-- Width is 57.143vh i.e. half of height (because grid dimensions are 4 ⨯ 2) -->
<div
diff --git a/test/playwright/README.md b/test/playwright/README.md
new file mode 100644
index 000000000..e1f0ca2aa
--- /dev/null
+++ b/test/playwright/README.md
@@ -0,0 +1,104 @@
+# Playwright tests
+
+Our Playwright test suite runs inside a docker container in order to prevent cross-platform browser differences from creating flaky test behavior. We run both end-to-end and visual-regression tests in the same container to save from having to run the Nuxt production build twice.
+
+Having docker and docker-compose is a pre-requisite to running the playwright tests locally. Please follow [the relevant instructions for your operating system for how to install docker and docker-compose](https://docs.docker.com/get-docker/). If you're on Windows 10 Home Edition, please note that you'll need to [install and run docker inside WSL2](https://www.freecodecamp.org/news/how-to-run-docker-on-windows-10-home-edition/). We strongly recommend (and only plan to support) Windows users run everything inside of WSL.
+
+If it's not possible for you to run docker locally, don't fret! Our CI will run it on every pull request and another contributor who is able to run the tests locally can help you develop new or update existing tests for your changes.
+
+The Playwright docker container runs everything needed for the end-to-end and visual-regression tests, including the Nuxt server and a [Talkback proxy](https://github.com/ijpiantanida/talkback) for the API. It will also generate and match against the existing visual-regression snapshots in the codebase.
+
+## Running the tests
+
+To run the end-to-end tests, after having installed docker, run the following:
+
+```bash
+pnpm test:playwright
+```
+
+You may pass arguments to playwright after a `--`, for example `-u` to update snapshots or a filter.
+
+```bash
+pnpm test:playwright -- visual-regression -u
+```
+
+The above will run only test files with `visual-regression` in the path and will update any snapshot tests due to the `-u` flag.
+
+## Visual Regression tests
+
+When writing visual regression tests, it is good practice to write tests for each relevant breakpoint. There is a series of helpers in [`./utils/breakpoints.ts`](./utils/breakpoints.ts) for this. The most common usage for this module is to run a test or set of tests for every breakpoint our app knows about or a subset of them. Occasionally you will need to separate tests by breakpoint or by range for which there are also helpers.
+
+Each of the following methods expects a describe block callback function accepting some useful helpers.
+
+- `breakpoints.describeEvery`: Generates a describe block for every breakpoint our app is concerned with.
+- `breakpoints.describeEachDesktop`: Generates a describe block for every breakpoint that roughly correlates with desktop and tablet width devices.
+- `breakpoints.describeEachMobile`: Generates a describe block for every breakpoint that roughly correlates with smartphone sized mobile devices.
+- `breakpoints.describeEachBreakpoint`: Accepts a list of breakpoints to generate describe blocks for, with similar syntax to `jest`'s `test.each` helper. Used like `breakpoints.describeEachBreakpoint(['xs', '2xl'])(<block>)`. `describeEvery` and the two `describeEach*` methods are aliases for pre-configured `describeEachBreakpoint`. It is unlikely that you will need to use this helper directly.
+
+Additionally there are describe blocks for individual breakpoints, each following the pattern `` `describe${Capitalize<Breakpoint>}` ``, for example `breakpoints.describeXs`.
+
+The describe blocks are passed the following helpers:
+
+- `breakpoint`: The name of the breakpoint for the current describe block.
+- `getConfigValues`: Returns useful configuration values if running a snapshot test manually.
+- `expectSnapshot`: A function accepting an identifier and a screenshot-able object. This will generate the screenshot and match it against a snapshot matching the name passed. Remember to `await` this function or else the `expect` will not be fired within the context of the test (you'll get a nasty error in this case).
+
+Please see the [`homepage.spec.ts` visual-regression tests](./visual-regression/homepage.spec.ts) as an example of how to use these helpers.
+
+### What to test for visual regression
+
+Visual regression tests can match entire pages or on individual elements in specific states. They're useful, for example, to test the various focus, hover, and active states of interactive elements. Use [`page.locator`](https://playwright.dev/docs/api/class-page#page-locator) to select specific elements to pass to `expectSnapshot`.
+
+## API proxy
+
+The Playwright test container also runs an API proxy using [Talkback](https://github.com/ijpiantanida/talkback) to prevent network requests from hitting the live API during end-to-end and visual-regression tests. This significantly speeds up the tests and makes the data being tested against consistent across test runs and eliminates variations that the API may include after data refreshes happen.
+
+The configuration for the Talkback proxy is in the [`proxy.js`](../proxy.js) module and is run using `pnpm talkback`. It is rare and unlikely that you will need to run it directly as running it is handled by the Playwright `webServer` configuration.
+
+If you've added new tests or updated existing ones, you may get errors about API responses not being found. To remedy this, you'll need to update the tapes:
+
+```bash
+pnpm test:playwright:update-tapes
+```
+
+If for some reason you find yourself needing to completely recreate the tapes, you may do so using the `test:playwright:recreate-tapes` script. Please use this sparingly as it creates massive diffs in PRs (tens of thousands of lines across over literally hundreds of JSON files). Note that you may be rate-limited by the upstream production API if you do this. There is no official workaround for this at the moment.
+
+## Debugging
+
+Additional debugging may be accomplished in two ways. You may inspect the trace output of failed tests by finding the `trace.zip` for the relevant test in the `test-results` folder. Traces are only saved for failed tests. You can use the [Playwright Trace Viewer](https://playwright.dev/docs/trace-viewer) to inspect these (or open the zip yourself and poke around the files on your own).
+
+Visual regression tests that fail to match the existing snapshots will also have `expected`, `actual` and `diff` files generated that are helpful for understanding why intermittent failures are happening. These are generated automatically by Playwright and will be placed in the `test-results` folder under the fully qualified name of the test that failed (with every parent describe block included).
+
+Additionally, you can run run the tests in debug mode. This will run the tests with a headed browser as opposed to a headless (invisible) one and allow you to watch the test happen in real time. It's not possible for a headed browser to run inside the docker container, however, so be aware that when debugging the environment will be slightly different. For example, if you're on any OS other than Linux, the browser you're running will have small differences in how it renders the page compared to the docker container.
+
+To run the debug tests:
+
+```bash
+pnpm test:playwright:debug
+```
+
+Note that this still runs the talkback proxy and the Nuxt server for you. If you'd like to avoid this, simply run the Nuxt server before you run the `test:playwright:debug` script and Playwright will automatically prefer your previously running Nuxt server.
+
+<aside>
+For some reason the following two tests are consistently flaky when updating tapes but appear to be stable when running the e2e tapes with pre-existing tapes.
+
+```
+search-types.spec.js:102:3 › Can open All content page client-side
+search-types.spec.js:102:3 › Can open Images page client-side
+```
+
+Don't be alarmed if you notice this.
+
+</aside>
+
+## Generating new tests
+
+When writing end-to-end tests, it can be helpful to use Playwright [codegen](https://playwright.dev/docs/cli#generate-code) to generate the tests by performing actions in the browser:
+
+```
+pnpm run generate-playwright-tests
+```
+
+This will open the app in a new browser window, and record any actions you take in a format that can be used in end-to-end tests.
+
+Note that this does _not_ run the server for you; you must run the Nuxt server using `pnpm start` or `pnpm dev` separately before running the codegen script.
diff --git a/test/e2e/filters.spec.js b/test/playwright/e2e/filters.spec.ts
similarity index 82%
rename from test/e2e/filters.spec.js
rename to test/playwright/e2e/filters.spec.ts
index fe6ce0d51..181d6e346 100644
--- a/test/e2e/filters.spec.js
+++ b/test/playwright/e2e/filters.spec.ts
@@ -1,30 +1,30 @@
-const { test, expect } = require('@playwright/test')
+import { test, expect, Page } from '@playwright/test'
-const {
+import {
assertCheckboxStatus,
openFilters,
- mockProviderApis,
changeContentType,
-} = require('./utils')
+} from '~~/test/playwright/utils/navigation'
-// Cannot require media constants because they use `export`
-const ALL_MEDIA = 'all'
-const AUDIO = 'audio'
-const IMAGE = 'image'
-const supportedSearchTypes = [ALL_MEDIA, AUDIO, IMAGE]
+import { mockProviderApis } from '~~/test/playwright/utils/route'
+
+import {
+ supportedSearchTypes,
+ ALL_MEDIA,
+ IMAGE,
+ AUDIO,
+} from '~/constants/media'
test.beforeEach(async ({ context }) => {
await mockProviderApis(context)
})
-/**
- * @param page
- * @param {'checked'|'notChecked'|'total'} checked
- * @param {number} count
- * @returns {Promise<void>}
- */
-const assertCheckboxCount = async (page, checked, count) => {
- let checkedString = {
+const assertCheckboxCount = async (
+ page: Page,
+ checked: 'checked' | 'notChecked' | 'total',
+ count: number
+) => {
+ const checkedString = {
checked: ':checked',
notChecked: ':not(:checked)',
total: '',
@@ -60,10 +60,11 @@ test('initial filters are applied based on the url', async ({ page }) => {
await openFilters(page)
const expectedFilters = ['cc0', 'commercial', 'creator']
- for (let checkbox of expectedFilters) {
+ for (const checkbox of expectedFilters) {
await assertCheckboxStatus(page, checkbox)
}
})
+
test('common filters are retained when media type changes from all media to single type', async ({
page,
}) => {
@@ -73,7 +74,7 @@ test('common filters are retained when media type changes from all media to sing
await openFilters(page)
const expectedFilters = ['cc0', 'commercial', 'creator']
- for (let checkbox of expectedFilters) {
+ for (const checkbox of expectedFilters) {
await assertCheckboxStatus(page, checkbox)
}
await changeContentType(page, 'Images')
@@ -81,7 +82,7 @@ test('common filters are retained when media type changes from all media to sing
await expect(page).toHaveURL(
'/search/image?q=cat&license_type=commercial&license=cc0&searchBy=creator'
)
- for (let checkbox of expectedFilters) {
+ for (const checkbox of expectedFilters) {
await assertCheckboxStatus(page, checkbox)
}
})
@@ -94,13 +95,13 @@ test('common filters are retained when media type changes from single type to al
)
await openFilters(page)
- for (let checkbox of ['cc0', 'commercial', 'creator']) {
+ for (const checkbox of ['cc0', 'commercial', 'creator']) {
await assertCheckboxStatus(page, checkbox)
}
await changeContentType(page, 'All content')
- for (let checkbox of ['cc0', 'commercial', 'creator']) {
+ for (const checkbox of ['cc0', 'commercial', 'creator']) {
await assertCheckboxStatus(page, checkbox)
}
await expect(page).toHaveURL(
@@ -117,7 +118,7 @@ test('selecting some filters can disable dependent filters', async ({
// by-nc is special because we normally test for fuzzy match, and by-nc matches 3 labels.
const byNc = page.locator('input[value="by-nc"]')
await expect(byNc).toBeDisabled()
- for (let checkbox of ['by-nc-sa', 'by-nc-nd']) {
+ for (const checkbox of ['by-nc-sa', 'by-nc-nd']) {
await assertCheckboxStatus(page, checkbox, 'disabled')
}
await assertCheckboxStatus(page, 'commercial')
@@ -126,7 +127,7 @@ test('selecting some filters can disable dependent filters', async ({
await assertCheckboxStatus(page, 'commercial', 'unchecked')
await expect(byNc).not.toBeDisabled()
- for (let checkbox of ['commercial', 'by-nc-sa', 'by-nc-nd']) {
+ for (const checkbox of ['commercial', 'by-nc-sa', 'by-nc-nd']) {
await assertCheckboxStatus(page, checkbox, 'unchecked')
}
})
diff --git a/test/e2e/homepage.spec.js b/test/playwright/e2e/homepage.spec.ts
similarity index 92%
rename from test/e2e/homepage.spec.js
rename to test/playwright/e2e/homepage.spec.ts
index 2bcca0373..4556863f5 100644
--- a/test/e2e/homepage.spec.js
+++ b/test/playwright/e2e/homepage.spec.ts
@@ -1,6 +1,6 @@
-const { test, expect } = require('@playwright/test')
+import { test, expect } from '@playwright/test'
-const { mockProviderApis } = require('./utils')
+import { mockProviderApis } from '~~/test/playwright/utils/route'
test.beforeEach(async ({ context }) => {
await mockProviderApis(context)
diff --git a/test/e2e/image-detail.spec.js b/test/playwright/e2e/image-detail.spec.ts
similarity index 88%
rename from test/e2e/image-detail.spec.js
rename to test/playwright/e2e/image-detail.spec.ts
index 1523eb44f..353b81722 100644
--- a/test/e2e/image-detail.spec.js
+++ b/test/playwright/e2e/image-detail.spec.ts
@@ -1,13 +1,13 @@
-const { test, expect } = require('@playwright/test')
+import { test, expect, Page } from '@playwright/test'
-const { mockProviderApis } = require('./utils')
+import { mockProviderApis } from '~~/test/playwright/utils/route'
-const goToCustomImagePage = async (page) => {
+const goToCustomImagePage = async (page: Page) => {
// Test in a custom image detail page, it should apply the same for any image.
await page.goto('image/e9d97a98-621b-4ec2-bf70-f47a74380452')
}
-const showsErrorPage = async (page) => {
+const showsErrorPage = async (page: Page) => {
await expect(page.locator('h1')).toHaveText(
/The content you’re looking for seems to have disappeared/
)
diff --git a/test/e2e/migration-banner.spec.js b/test/playwright/e2e/migration-banner.spec.ts
similarity index 86%
rename from test/e2e/migration-banner.spec.js
rename to test/playwright/e2e/migration-banner.spec.ts
index 63a924361..2b7145386 100644
--- a/test/e2e/migration-banner.spec.js
+++ b/test/playwright/e2e/migration-banner.spec.ts
@@ -1,4 +1,4 @@
-const { test, expect } = require('@playwright/test')
+import { test, expect } from '@playwright/test'
test('shows migration banner on homepage', async ({ page }) => {
await page.goto('/?referrer=creativecommons.org')
@@ -13,7 +13,7 @@ test('shows migration banner on homepage', async ({ page }) => {
test('migration banner goes away on navigation', async ({ page }) => {
await page.goto('/?referrer=creativecommons.org')
- let migrationNotice = page.locator('.cc-ov-migration')
+ const migrationNotice = page.locator('.cc-ov-migration')
await expect(migrationNotice).toBeVisible()
// Navigate away from the page
diff --git a/test/e2e/resources/last_page.json b/test/playwright/e2e/resources/last_page.json
similarity index 100%
rename from test/e2e/resources/last_page.json
rename to test/playwright/e2e/resources/last_page.json
diff --git a/test/e2e/resources/mock_audio_data.json b/test/playwright/e2e/resources/mock_audio_data.json
similarity index 100%
rename from test/e2e/resources/mock_audio_data.json
rename to test/playwright/e2e/resources/mock_audio_data.json
diff --git a/test/e2e/resources/mock_image_data.json b/test/playwright/e2e/resources/mock_image_data.json
similarity index 100%
rename from test/e2e/resources/mock_image_data.json
rename to test/playwright/e2e/resources/mock_image_data.json
diff --git a/test/e2e/resources/sample_image.jpg b/test/playwright/e2e/resources/sample_image.jpg
similarity index 100%
rename from test/e2e/resources/sample_image.jpg
rename to test/playwright/e2e/resources/sample_image.jpg
diff --git a/test/e2e/search-navigation.spec.js b/test/playwright/e2e/search-navigation.spec.ts
similarity index 88%
rename from test/e2e/search-navigation.spec.js
rename to test/playwright/e2e/search-navigation.spec.ts
index 8cd18d4a7..3a7fde2a6 100644
--- a/test/e2e/search-navigation.spec.js
+++ b/test/playwright/e2e/search-navigation.spec.ts
@@ -1,10 +1,10 @@
-const { expect, test } = require('@playwright/test')
+import { expect, test } from '@playwright/test'
-const { openFilters } = require('./utils')
+import { openFilters } from '~~/test/playwright/utils/navigation'
+import { mockProviderApis } from '~~/test/playwright/utils/route'
test.beforeEach(async ({ context }) => {
- await context.route('**.jamendo.**', (r) => r.abort())
- await context.route('**.freesound.**', (r) => r.abort())
+ mockProviderApis(context)
})
test.describe('search history navigation', () => {
diff --git a/test/e2e/search-query-client.spec.js b/test/playwright/e2e/search-query-client.spec.ts
similarity index 93%
rename from test/e2e/search-query-client.spec.js
rename to test/playwright/e2e/search-query-client.spec.ts
index 56b233c64..e819d4b04 100644
--- a/test/e2e/search-query-client.spec.js
+++ b/test/playwright/e2e/search-query-client.spec.ts
@@ -1,6 +1,7 @@
-const { test, expect } = require('@playwright/test')
+import { test, expect } from '@playwright/test'
-const { mockProviderApis, changeContentType } = require('./utils')
+import { changeContentType } from '~~/test/playwright/utils/navigation'
+import { mockProviderApis } from '~~/test/playwright/utils/route'
/**
* When navigating to the search page on the client side:
diff --git a/test/e2e/search-query-server.spec.js b/test/playwright/e2e/search-query-server.spec.ts
similarity index 85%
rename from test/e2e/search-query-server.spec.js
rename to test/playwright/e2e/search-query-server.spec.ts
index d40c09cfd..970074f95 100644
--- a/test/e2e/search-query-server.spec.js
+++ b/test/playwright/e2e/search-query-server.spec.ts
@@ -1,7 +1,11 @@
-const { test, expect } = require('@playwright/test')
+import { test, expect } from '@playwright/test'
-const { mockProviderApis, openFilters } = require('./utils')
-const { currentContentType, assertCheckboxStatus } = require('./utils')
+import {
+ openFilters,
+ currentContentType,
+ assertCheckboxStatus,
+} from '~~/test/playwright/utils/navigation'
+import { mockProviderApis } from '~~/test/playwright/utils/route'
/**
* URL is correctly converted into search state:
@@ -36,7 +40,7 @@ test('url path /search/ is used to select `all` search tab', async ({
await page.goto('/search/?q=cat')
const contentType = await currentContentType(page)
- expect(contentType.trim()).toEqual('All content')
+ expect(contentType?.trim()).toEqual('All content')
})
test('url path /search/audio is used to select `audio` search tab', async ({
@@ -46,7 +50,7 @@ test('url path /search/audio is used to select `audio` search tab', async ({
await page.goto(audioSearchUrl)
const contentType = await currentContentType(page)
- expect(contentType.trim()).toEqual('Audio')
+ expect(contentType?.trim()).toEqual('Audio')
})
test('url query to filter, all tab, one parameter per filter type', async ({
@@ -57,7 +61,7 @@ test('url query to filter, all tab, one parameter per filter type', async ({
)
await openFilters(page)
- for (let checkbox of ['cc0', 'commercial', 'creator']) {
+ for (const checkbox of ['cc0', 'commercial', 'creator']) {
await assertCheckboxStatus(page, checkbox)
}
})
@@ -70,7 +74,7 @@ test('url query to filter, image tab, several filters for one filter type select
)
await openFilters(page)
const checkboxes = ['jpeg', 'png', 'gif', 'svgs']
- for (let checkbox of checkboxes) {
+ for (const checkbox of checkboxes) {
await assertCheckboxStatus(page, checkbox)
}
})
diff --git a/test/e2e/search-types.spec.js b/test/playwright/e2e/search-types.spec.ts
similarity index 71%
rename from test/e2e/search-types.spec.js
rename to test/playwright/e2e/search-types.spec.ts
index fa4d6ffa7..8494d09a9 100644
--- a/test/e2e/search-types.spec.js
+++ b/test/playwright/e2e/search-types.spec.ts
@@ -1,6 +1,6 @@
-const { test, expect } = require('@playwright/test')
+import { test, expect, Page } from '@playwright/test'
-const { changeContentType } = require('./utils')
+import { changeContentType } from '~~/test/playwright/utils/navigation'
/**
* Using SSR:
@@ -23,34 +23,38 @@ test.beforeEach(async ({ context }) => {
await context.route('**.jamendo.com**', (route) => route.abort())
})
-const searchTypes = [
- {
- id: 'all',
- name: 'All content',
- url: '/search/?q=birds',
- canLoadMore: true,
- metaSourceCount: 7,
- },
- {
- id: 'image',
- name: 'Images',
- url: '/search/image?q=birds',
- canLoadMore: true,
- metaSourceCount: 7,
- results: /Over 10,000 results/,
- },
- {
- id: 'audio',
- name: 'Audio',
- url: '/search/audio?q=birds',
- canLoadMore: true,
- metaSourceCount: 3,
- results: /93 results/,
- },
-]
-
-async function checkLoadMore(page, searchType) {
- const loadMoreSection = await page.locator('[data-testid="load-more"]')
+const allContentConfig = {
+ id: 'all',
+ name: 'All content',
+ url: '/search/?q=birds',
+ canLoadMore: true,
+ metaSourceCount: 7,
+} as const
+
+const imageConfig = {
+ id: 'image',
+ name: 'Images',
+ url: '/search/image?q=birds',
+ canLoadMore: true,
+ metaSourceCount: 7,
+ results: /Over 10,000 results/,
+} as const
+
+const audioConfig = {
+ id: 'audio',
+ name: 'Audio',
+ url: '/search/audio?q=birds',
+ canLoadMore: true,
+ metaSourceCount: 3,
+ results: /93 results/,
+} as const
+
+const searchTypes = [allContentConfig, imageConfig, audioConfig] as const
+
+type SearchTypeConfig = typeof searchTypes[number]
+
+async function checkLoadMore(page: Page, searchType: SearchTypeConfig) {
+ const loadMoreSection = page.locator('[data-testid="load-more"]')
if (!searchType.canLoadMore) {
// When we expect the section not to be here, the test becomes very slow because
// it waits until the end of the timeout (5 seconds).
@@ -60,7 +64,7 @@ async function checkLoadMore(page, searchType) {
await expect(loadMoreSection).toContainText('Load more')
}
}
-async function checkMetasearchForm(page, searchType) {
+async function checkMetasearchForm(page: Page, searchType: SearchTypeConfig) {
const metaSearchForm = await page.locator('[data-testid="meta-search-form"]')
await expect(metaSearchForm).toHaveCount(1)
@@ -68,7 +72,7 @@ async function checkMetasearchForm(page, searchType) {
await expect(sourceButtons).toHaveCount(searchType.metaSourceCount)
}
-async function checkSearchMetadata(page, searchType) {
+async function checkSearchMetadata(page: Page, searchType: SearchTypeConfig) {
if (searchType.canLoadMore) {
const searchResult = await page.locator('[data-testid="search-results"]')
await expect(searchResult).toBeVisible()
@@ -76,7 +80,7 @@ async function checkSearchMetadata(page, searchType) {
}
}
-async function checkPageMeta(page, searchType) {
+async function checkPageMeta(page: Page, searchType: SearchTypeConfig) {
const urlParam = searchType.id === 'all' ? '' : searchType.id
const expectedTitle = `birds | Openverse`
@@ -85,7 +89,7 @@ async function checkPageMeta(page, searchType) {
await expect(page).toHaveTitle(expectedTitle)
await expect(page).toHaveURL(expectedURL)
}
-async function checkSearchResult(page, searchType) {
+async function checkSearchResult(page: Page, searchType: SearchTypeConfig) {
await checkSearchMetadata(page, searchType)
await checkLoadMore(page, searchType)
await checkMetasearchForm(page, searchType)
@@ -108,8 +112,10 @@ for (const searchType of searchTypes) {
})
}
-for (let searchTypeName of ['audio', 'image']) {
- const searchType = searchTypes.find((type) => type.id === searchTypeName)
+for (const searchTypeName of ['audio', 'image'] as const) {
+ const searchType = searchTypes.find((type) => type.id === searchTypeName) as
+ | typeof audioConfig
+ | typeof imageConfig
test(`Can open ${searchTypeName} page from the all view`, async ({
page,
}) => {
diff --git a/test/e2e/search.spec.js b/test/playwright/e2e/search.spec.ts
similarity index 92%
rename from test/e2e/search.spec.js
rename to test/playwright/e2e/search.spec.ts
index c1ac308b1..5c76053bd 100644
--- a/test/e2e/search.spec.js
+++ b/test/playwright/e2e/search.spec.ts
@@ -6,9 +6,9 @@
* When pending: does not show 'No images', Safer Browsing, search rating or error message
* On error: shows error message
*/
-const { expect, test } = require('@playwright/test')
+import { expect, test } from '@playwright/test'
-const { mockProviderApis } = require('./utils')
+import { mockProviderApis } from '~~/test/playwright/utils/route'
test.beforeEach(async ({ context }) => {
await mockProviderApis(context)
@@ -54,7 +54,7 @@ test('navigates to the image detail page correctly', async ({ page }) => {
await page.locator('#main-image').waitFor()
const headingText = await page.locator('h1').textContent()
- expect(headingText.trim().toLowerCase()).toEqual(imgTitle.toLowerCase())
+ expect(headingText?.trim().toLowerCase()).toEqual(imgTitle?.toLowerCase())
// Renders the breadcrumb link
await expect(page.locator('text="Back to search results"')).toBeVisible()
})
diff --git a/test/e2e/translation-banner.spec.js b/test/playwright/e2e/translation-banner.spec.ts
similarity index 95%
rename from test/e2e/translation-banner.spec.js
rename to test/playwright/e2e/translation-banner.spec.ts
index dddaad170..cee5733cc 100644
--- a/test/e2e/translation-banner.spec.js
+++ b/test/playwright/e2e/translation-banner.spec.ts
@@ -1,4 +1,4 @@
-const { test, expect } = require('@playwright/test')
+import { test, expect } from '@playwright/test'
test('Can see the translation banner and go to the correct link', async ({
page,
diff --git a/test/e2e/playwright.config.ts b/test/playwright/playwright.config.ts
similarity index 93%
rename from test/e2e/playwright.config.ts
rename to test/playwright/playwright.config.ts
index 7c4b3bc49..77e0c447e 100644
--- a/test/e2e/playwright.config.ts
+++ b/test/playwright/playwright.config.ts
@@ -1,7 +1,15 @@
+import path from 'path'
+
+import { addAliases } from 'module-alias'
+
import type { PlaywrightTestConfig } from '@playwright/test'
+addAliases({
+ '~': path.resolve(process.cwd(), 'src'),
+ '~~': process.cwd(),
+})
+
const config: PlaywrightTestConfig = {
- testDir: '.',
webServer: {
/**
* Note: You can speed up local testing by switching `prod` out for `start`
diff --git a/test/playwright/utils/breakpoints.ts b/test/playwright/utils/breakpoints.ts
new file mode 100644
index 000000000..fd2975df6
--- /dev/null
+++ b/test/playwright/utils/breakpoints.ts
@@ -0,0 +1,106 @@
+import { test, expect } from '@playwright/test'
+
+import {
+ Breakpoints as AllBreakpoints,
+ SCREEN_SIZES,
+} from '~/constants/screens'
+
+type Breakpoint = Exclude<AllBreakpoints, 'mob'>
+
+type ScreenshotAble = {
+ screenshot(): Promise<Buffer>
+}
+
+type ExpectSnapshot = (name: string, s: ScreenshotAble) => Promise<Buffer>
+
+type BreakpointBlock = (options: {
+ getConfigValues: (name: string) => {
+ name: `${typeof name}-${Breakpoint}.png`
+ }
+ breakpoint: Breakpoint
+ expectSnapshot: ExpectSnapshot
+}) => void
+
+const desktopBreakpoints = ['2xl', 'xl', 'lg', 'md'] as const
+const mobileBreakpoints = ['sm', 'xs'] as const
+
+// For desktop UA use the default
+const desktopUa = undefined
+const mobileUa =
+ 'Mozilla/5.0 (Android 7.0; Mobile; rv:54.0) Gecko/54.0 Firefox/54.0'
+
+const mockUaStrings: Readonly<Record<Breakpoint, string | undefined>> =
+ Object.freeze(
+ Object.fromEntries([
+ ...desktopBreakpoints.map((b) => [b, desktopUa]),
+ ...mobileBreakpoints.map((b) => [b, mobileUa]),
+ ])
+ )
+
+const makeBreakpointDescribe =
+ (breakpoint: Breakpoint, screenWidth: number) => (block: BreakpointBlock) => {
+ test.describe(
+ `screen at breakpoint ${breakpoint} with width ${screenWidth}`,
+ () => {
+ test.use({
+ viewport: { width: screenWidth, height: 700 },
+ userAgent: mockUaStrings[breakpoint],
+ })
+ const getConfigValues = (name: string) => ({
+ name: `${name}-${breakpoint}.png` as const,
+ })
+ const expectSnapshot = async (
+ name: string,
+ screenshotAble: ScreenshotAble
+ ) => {
+ const { name: snapshotName } = getConfigValues(name)
+ return expect(await screenshotAble.screenshot()).toMatchSnapshot({
+ name: snapshotName,
+ })
+ }
+
+ block({ breakpoint, getConfigValues, expectSnapshot })
+ }
+ )
+ }
+
+const capitalize = (s: string): Capitalize<typeof s> =>
+ `${s[0].toUpperCase()}${s.slice(1)}`
+
+const breakpointTests = Array.from(SCREEN_SIZES.entries()).reduce(
+ (tests, [breakpoint, screenWidth]) =>
+ Object.assign(tests, {
+ [`describe${capitalize(breakpoint)}`]: makeBreakpointDescribe(
+ breakpoint,
+ screenWidth
+ ),
+ }),
+ {} as Record<
+ `describe${Capitalize<Breakpoint>}`,
+ ReturnType<typeof makeBreakpointDescribe>
+ >
+)
+
+const describeEachBreakpoint =
+ (breakpoints: readonly Breakpoint[]) => (block: BreakpointBlock) => {
+ Object.entries(breakpointTests).forEach(([bp, describe]) => {
+ if (
+ breakpoints.includes(
+ bp.replace('describe', '').toLowerCase() as Breakpoint
+ )
+ )
+ describe(block)
+ })
+ }
+
+const describeEvery = describeEachBreakpoint(Array.from(SCREEN_SIZES.keys()))
+const describeEachDesktop = describeEachBreakpoint(desktopBreakpoints)
+const describeEachMobile = describeEachBreakpoint(mobileBreakpoints)
+
+export default {
+ ...breakpointTests,
+ describeEachBreakpoint,
+ describeEvery,
+ describeEachDesktop,
+ describeEachMobile,
+}
diff --git a/test/e2e/utils.js b/test/playwright/utils/navigation.ts
similarity index 69%
rename from test/e2e/utils.js
rename to test/playwright/utils/navigation.ts
index 523d79157..87dfd8d73 100644
--- a/test/e2e/utils.js
+++ b/test/playwright/utils/navigation.ts
@@ -1,6 +1,6 @@
-const { expect } = require('@playwright/test')
+import { expect, Page } from '@playwright/test'
-const openFilters = async (page) => {
+export const openFilters = async (page: Page) => {
const filterButtonSelector =
'[aria-controls="filter-sidebar"], [aria-controls="filter-modal"]'
const isPressed = async () =>
@@ -11,7 +11,11 @@ const openFilters = async (page) => {
}
}
-const assertCheckboxStatus = async (page, label, status = 'checked') => {
+export const assertCheckboxStatus = async (
+ page: Page,
+ label: string,
+ status: 'checked' | 'unchecked' | 'disabled' = 'checked'
+) => {
const checkbox = page.locator(`label:has-text('${label}')`)
switch (status) {
case 'checked': {
@@ -30,32 +34,23 @@ const assertCheckboxStatus = async (page, label, status = 'checked') => {
}
}
-const changeContentType = async (page, to) => {
+export const changeContentType = async (
+ page: Page,
+ to: 'Audio' | 'Images' | 'All content'
+) => {
await page.click(
`button[aria-controls="content-switcher-popover"], button[aria-controls="content-switcher-modal"]`
)
await page.click(`a:has-text("${to}")`)
}
+
/**
* Finds a button with a popup to the left of the filters button which doesn't have a 'menu' label
- * @param page
- * @returns {Promise<string>}
+ * @param page - The current page
*/
-const currentContentType = async (page) => {
+export const currentContentType = async (page: Page) => {
const contentSwitcherButton = await page.locator(
`button[aria-controls="content-switcher-popover"], button[aria-controls="content-switcher-modal"]`
)
return contentSwitcherButton.textContent()
}
-
-const mockProviderApis = async (context) => {
- await context.route('**.jamendo.com**', (route) => route.abort())
-}
-
-module.exports = {
- openFilters,
- changeContentType,
- currentContentType,
- assertCheckboxStatus,
- mockProviderApis,
-}
diff --git a/test/playwright/utils/route.ts b/test/playwright/utils/route.ts
new file mode 100644
index 000000000..9cec9bbf0
--- /dev/null
+++ b/test/playwright/utils/route.ts
@@ -0,0 +1,6 @@
+import type { BrowserContext } from '@playwright/test'
+
+export const mockProviderApis = async (context: BrowserContext) => {
+ await context.route('**.jamendo.com**', (route) => route.abort())
+ await context.route('**.freesound.**', (r) => r.abort())
+}
diff --git a/test/playwright/visual-regression/homepage.spec.ts b/test/playwright/visual-regression/homepage.spec.ts
new file mode 100644
index 000000000..f3b8dae3e
--- /dev/null
+++ b/test/playwright/visual-regression/homepage.spec.ts
@@ -0,0 +1,75 @@
+import { test, Page } from '@playwright/test'
+
+import breakpoints from '~~/test/playwright/utils/breakpoints'
+
+const deleteImageCarousel = async (page: Page) => {
+ const element = await page.$('[data-testid="image-carousel"]')
+ await element?.evaluate((node) => node.remove())
+ element?.dispose()
+}
+
+test.describe('homepage snapshots', () => {
+ test.describe('ltr', () => {
+ test.beforeEach(async ({ page }) => {
+ await page.goto('/')
+ })
+
+ breakpoints.describeEachDesktop(({ expectSnapshot }) =>
+ test('full page', async ({ page }) => {
+ await deleteImageCarousel(page)
+ await expectSnapshot('index-ltr', page)
+ })
+ )
+
+ test.describe('search input', () => {
+ breakpoints.describeEvery(({ expectSnapshot }) => {
+ test('unfocused', async ({ page }) => {
+ await expectSnapshot(
+ 'unfocused-search-ltr',
+ page.locator('form:has(input)')
+ )
+ })
+
+ test('focused', async ({ page }) => {
+ await page.focus('input')
+ await expectSnapshot(
+ 'focused-search-ltr',
+ page.locator('form:has(input)')
+ )
+ })
+ })
+ })
+ })
+
+ test.describe('rtl', () => {
+ test.beforeEach(async ({ page }) => {
+ await page.goto('/ar')
+ })
+
+ breakpoints.describeEachDesktop(({ expectSnapshot }) =>
+ test('full page', async ({ page }) => {
+ await deleteImageCarousel(page)
+ await expectSnapshot('index-rtl', page)
+ })
+ )
+
+ test.describe('search input', () => {
+ breakpoints.describeEvery(({ expectSnapshot }) => {
+ test('unfocused', async ({ page }) => {
+ await expectSnapshot(
+ 'unfocused-search-rtl',
+ page.locator('form:has(input)')
+ )
+ })
+
+ test('focused', async ({ page }) => {
+ await page.focus('input')
+ await expectSnapshot(
+ 'focused-search-rtl',
+ page.locator('form:has(input)')
+ )
+ })
+ })
+ })
+ })
+})
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-ltr-2xl-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-ltr-2xl-linux.png
new file mode 100644
index 000000000..4f6079fd6
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-ltr-2xl-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-ltr-lg-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-ltr-lg-linux.png
new file mode 100644
index 000000000..2563a4268
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-ltr-lg-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-ltr-md-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-ltr-md-linux.png
new file mode 100644
index 000000000..3b64f56f5
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-ltr-md-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-ltr-sm-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-ltr-sm-linux.png
new file mode 100644
index 000000000..ad30069a1
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-ltr-sm-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-ltr-xl-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-ltr-xl-linux.png
new file mode 100644
index 000000000..dfc5e6aff
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-ltr-xl-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-ltr-xs-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-ltr-xs-linux.png
new file mode 100644
index 000000000..f01e25836
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-ltr-xs-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-rtl-2xl-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-rtl-2xl-linux.png
new file mode 100644
index 000000000..2203c3395
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-rtl-2xl-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-rtl-lg-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-rtl-lg-linux.png
new file mode 100644
index 000000000..d379754c7
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-rtl-lg-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-rtl-md-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-rtl-md-linux.png
new file mode 100644
index 000000000..29b1ae3f5
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-rtl-md-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-rtl-sm-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-rtl-sm-linux.png
new file mode 100644
index 000000000..39d1288ec
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-rtl-sm-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-rtl-xl-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-rtl-xl-linux.png
new file mode 100644
index 000000000..93145ffdc
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-rtl-xl-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-rtl-xs-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-rtl-xs-linux.png
new file mode 100644
index 000000000..fe064b6b4
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/focused-search-rtl-xs-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/index-ltr-2xl-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/index-ltr-2xl-linux.png
new file mode 100644
index 000000000..2cc49ca91
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/index-ltr-2xl-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/index-ltr-lg-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/index-ltr-lg-linux.png
new file mode 100644
index 000000000..35b8d61aa
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/index-ltr-lg-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/index-ltr-md-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/index-ltr-md-linux.png
new file mode 100644
index 000000000..3fd93048e
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/index-ltr-md-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/index-ltr-xl-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/index-ltr-xl-linux.png
new file mode 100644
index 000000000..5ac8c6f4f
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/index-ltr-xl-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/index-rtl-2xl-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/index-rtl-2xl-linux.png
new file mode 100644
index 000000000..45e6fe367
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/index-rtl-2xl-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/index-rtl-lg-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/index-rtl-lg-linux.png
new file mode 100644
index 000000000..665d9f609
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/index-rtl-lg-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/index-rtl-md-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/index-rtl-md-linux.png
new file mode 100644
index 000000000..8191b8595
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/index-rtl-md-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/index-rtl-xl-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/index-rtl-xl-linux.png
new file mode 100644
index 000000000..fd58eea2e
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/index-rtl-xl-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-ltr-2xl-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-ltr-2xl-linux.png
new file mode 100644
index 000000000..2da0bdc10
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-ltr-2xl-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-ltr-lg-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-ltr-lg-linux.png
new file mode 100644
index 000000000..bd6cdc847
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-ltr-lg-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-ltr-md-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-ltr-md-linux.png
new file mode 100644
index 000000000..14217a9a1
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-ltr-md-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-ltr-sm-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-ltr-sm-linux.png
new file mode 100644
index 000000000..7e1f3706f
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-ltr-sm-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-ltr-xl-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-ltr-xl-linux.png
new file mode 100644
index 000000000..bb827e337
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-ltr-xl-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-ltr-xs-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-ltr-xs-linux.png
new file mode 100644
index 000000000..838f3c382
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-ltr-xs-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-rtl-2xl-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-rtl-2xl-linux.png
new file mode 100644
index 000000000..b461f659a
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-rtl-2xl-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-rtl-lg-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-rtl-lg-linux.png
new file mode 100644
index 000000000..f3a8d9e8f
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-rtl-lg-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-rtl-md-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-rtl-md-linux.png
new file mode 100644
index 000000000..b22718d0a
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-rtl-md-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-rtl-sm-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-rtl-sm-linux.png
new file mode 100644
index 000000000..d48a1c88b
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-rtl-sm-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-rtl-xl-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-rtl-xl-linux.png
new file mode 100644
index 000000000..b22718d0a
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-rtl-xl-linux.png differ
diff --git a/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-rtl-xs-linux.png b/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-rtl-xs-linux.png
new file mode 100644
index 000000000..8363b9900
Binary files /dev/null and b/test/playwright/visual-regression/homepage.spec.ts-snapshots/unfocused-search-rtl-xs-linux.png differ