visit
First of all, you have to run the application, so type in your terminal npm run dev
, and you will have your application up and running at the address //localhost:5173
.
Now you have to run the Playwright code generator. To do that, you have to open another tab in your terminal and type npx playwright codegen
. This command opens a new browser and the Playwright inspector.
Now, the browser shows an empty tab, and the Playwright inspector is on a new page, ready to listen to what you will do in the browser. If you go into the browser's address bar and type //localhost:5173,
you can notice that something has changed in the Playwright Inspector. The inspector noted the page change and added this step to the test body.
test('test', async ({ page }) => {
await page.goto('//localhost:5173/');
await page.locator('._Square_pba4r_1').first().click();
await page.locator('button:nth-child(5)').click();
await page.locator('button:nth-child(6)').click();
await page.locator('button:nth-child(7)').click();
await page.locator('button:nth-child(3)').click();
await page.locator('button:nth-child(9)').click();
await page.locator('button:nth-child(2)').click();
});
Let's start by changing the test name from test
to should win the player "X"
and changing the goto value from //localhost:5173/
to /
because our base root corresponds to the home page.
Then refactoring the first click probably is a good refactor to improve the test, so you have to change the line from await page.locator('._Square_pba4r_1').first().click();
to await page.locator("button:nth-child(1)").click();
and last but not least, add the assertion. In this case, if the test name is should win the player "X"
the best assertion is something like this
const winnerParagraph = await page.getByText(/winner/i);
await expect(winnerParagraph).toContainText("X");
So the code tries to get the paragraph with the winner text and checks if the value contains the X
value.The final result is this
test('should win the player "X"', async ({ page }) => {
await page.goto("/");
await page.locator("button:nth-child(1)").click();
await page.locator("button:nth-child(5)").click();
await page.locator("button:nth-child(6)").click();
await page.locator("button:nth-child(7)").click();
await page.locator("button:nth-child(3)").click();
await page.locator("button:nth-child(9)").click();
await page.locator("button:nth-child(2)").click();
const winnerParagraph = await page.getByText(/winner/i);
await expect(winnerParagraph).toContainText("X");
});