A Playwright locator identifies elements in a page’s DOM so an end-to-end test can inspect or interact with them. Create it after navigating with page.goto, then reuse it for assertions or actions. section 9.8.5
Build a locator incrementally:
- Select a collection with page.locator("#video-list>div"). section 9.8.5
- Assert its size with expect(videos).toHaveCount(2). section 9.8.5
- Narrow to one result with videos.nth(0).locator("a"), then inspect text and attributes or click it. section 9.8.5
Check the first video link
const videos = page.locator("#video-list>div"); const firstVideo = videos.nth(0).locator("a"); await expect(firstVideo).toHaveText("SampleVideo_1280x720_1mb.mp4"); await firstVideo.click(); section 9.8.5
Listing 9.13 An end-to-end test of FlixTube with Playwright
const { test, expect } = require('@playwright/test'); #1 const { describe } = test; #1 const { loadFixture } = require('./lib/db-fixture'); #2 describe("flixtube front end", () => { #3 test("can list videos", async ({ page }) => { #4 await loadFixture("metadata", "two-videos"); #5 await page.goto(`/`); #6 const videos = page.locator("#video-list>div"); #7 await expect(videos).toHaveCount(2); #8 const firstVideo = videos.nth(0).locator("a"); await expect(firstVideo) .toHaveText("SampleVideo_1280x720_1mb.mp4"); #9 await expect(firstVideo).toHaveAttribute("href", #9 "/video?id=5ea234a1c34230004592eb32" ); const secondVideo = videos.nth(1).locator("a"); await expect(secondVideo) .toHaveText("Another video.mp4"); #10 await expect(secondVideo).toHaveAttribute("href", #10 "/video?id=5ea234a5c34230004592eb33" ); }); #11 }); #1 Imports functions for building our tests. Note that we didn't have to import these functions with Jest, but we do with Playwright. #2 Imports a function that can load database fixtures #3 Defines the test suite #4 Tests that we can load the list of videos in the FlixTube UI #5 Loads the fixture named two-videos into the videos collection of the metadata database #6 Visits the Flixtube web page (the base URL is set in the Playwright configuration file). #7 Gets video elements from the page (they are HTML divs). #8 Checks that two videos (loaded from the database fixture) are displayed in the UI #9 Verifies the details displayed for the first video #10 Verifies the details displayed for the second video #11 Other tests go here.
Use the complete end-to-end listing to see locator creation connected to fixture loading, navigation, assertions, and browser interaction. section 9.8.5
