Interacting with UI Elements
When you write end-to-end tests for React applications using Playwright, the ability to reliably select and interact with UI elements is essential. Playwright provides several selector strategies, each with its own strengths and best use cases. Understanding these will help you write robust and maintainable tests.
The most common Playwright selectors are:
- Text selectors: these allow you to target elements by their visible text content. For instance, if you want to find a button labeled
Submit, you can use a selector likebutton:has-text("Submit"). This approach is user-centric, as it mimics how a user perceives the UI; - CSS selectors: these are based on the element's CSS classes, IDs, or tag names. For example,
.login-form input[type="email"]selects an email input inside a form with thelogin-formclass. CSS selectors are powerful and flexible, but they can be brittle if your styles or markup change frequently; - Data-testid selectors: by adding a
data-testidattribute to your elements, you can create stable hooks for your tests. For example,<button data-testid="submit-btn">Submit</button>can be selected with[data-testid="submit-btn"]. This method is highly recommended for React apps, as it decouples your tests from UI changes and focuses on elements intended for testing; - Accessibility selectors: these leverage ARIA roles, labels, or attributes to find elements. You might select a button with a specific role or
aria-label. Using accessibility selectors not only makes your tests more resilient, but also encourages you to build accessible applications.
Once you have selected the right element, Playwright enables you to simulate a wide range of user actions. These actions help you mimic real user behavior and verify that your React components respond as expected.
To simulate a click, you can use the click() method on a locator. This triggers the same events as a real mouse click. For entering text, the fill() method sets the value of an input field, while type() simulates key-by-key typing, including triggering keyboard events. If you need to submit a form, you can either click the submit button or use the press("Enter") method on an input field. For more advanced scenarios, you can simulate keyboard events such as pressing arrow keys or shortcuts using the press() method with the desired key.
By combining these selector and interaction techniques, you can write comprehensive tests that cover a variety of user flows in your React app.
src/App.jsx
export default function App() {
return (
<main style={{ padding: 24 }}>
<h1>Login</h1>
<form className="login-form">
<label>
Email
<input
type="email"
aria-label="Email address"
data-testid="email-input"
/>
</label>
<label>
Password
<input
type="password"
data-testid="password-input"
/>
</label>
<button type="submit" data-testid="submit-btn">
Submit
</button>
</form>
</main>
);
}
e2e/tests/interacting-with-ui.spec.ts
import { test, expect } from "@playwright/test";
test("user can interact with login form", async ({ page }) => {
await page.goto("/");
// Accessibility selector
await page.getByRole("heading", { name: "Login" }).isVisible();
// data-testid selector
await page.getByTestId("email-input").fill("test@example.com");
await page.getByTestId("password-input").fill("secret123");
// Text selector
await page.getByText("Submit").click();
// Basic assertion
await expect(page.getByTestId("submit-btn")).toBeVisible();
});
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo
Incrível!
Completion taxa melhorada para 6.67
Interacting with UI Elements
Deslize para mostrar o menu
When you write end-to-end tests for React applications using Playwright, the ability to reliably select and interact with UI elements is essential. Playwright provides several selector strategies, each with its own strengths and best use cases. Understanding these will help you write robust and maintainable tests.
The most common Playwright selectors are:
- Text selectors: these allow you to target elements by their visible text content. For instance, if you want to find a button labeled
Submit, you can use a selector likebutton:has-text("Submit"). This approach is user-centric, as it mimics how a user perceives the UI; - CSS selectors: these are based on the element's CSS classes, IDs, or tag names. For example,
.login-form input[type="email"]selects an email input inside a form with thelogin-formclass. CSS selectors are powerful and flexible, but they can be brittle if your styles or markup change frequently; - Data-testid selectors: by adding a
data-testidattribute to your elements, you can create stable hooks for your tests. For example,<button data-testid="submit-btn">Submit</button>can be selected with[data-testid="submit-btn"]. This method is highly recommended for React apps, as it decouples your tests from UI changes and focuses on elements intended for testing; - Accessibility selectors: these leverage ARIA roles, labels, or attributes to find elements. You might select a button with a specific role or
aria-label. Using accessibility selectors not only makes your tests more resilient, but also encourages you to build accessible applications.
Once you have selected the right element, Playwright enables you to simulate a wide range of user actions. These actions help you mimic real user behavior and verify that your React components respond as expected.
To simulate a click, you can use the click() method on a locator. This triggers the same events as a real mouse click. For entering text, the fill() method sets the value of an input field, while type() simulates key-by-key typing, including triggering keyboard events. If you need to submit a form, you can either click the submit button or use the press("Enter") method on an input field. For more advanced scenarios, you can simulate keyboard events such as pressing arrow keys or shortcuts using the press() method with the desired key.
By combining these selector and interaction techniques, you can write comprehensive tests that cover a variety of user flows in your React app.
src/App.jsx
export default function App() {
return (
<main style={{ padding: 24 }}>
<h1>Login</h1>
<form className="login-form">
<label>
Email
<input
type="email"
aria-label="Email address"
data-testid="email-input"
/>
</label>
<label>
Password
<input
type="password"
data-testid="password-input"
/>
</label>
<button type="submit" data-testid="submit-btn">
Submit
</button>
</form>
</main>
);
}
e2e/tests/interacting-with-ui.spec.ts
import { test, expect } from "@playwright/test";
test("user can interact with login form", async ({ page }) => {
await page.goto("/");
// Accessibility selector
await page.getByRole("heading", { name: "Login" }).isVisible();
// data-testid selector
await page.getByTestId("email-input").fill("test@example.com");
await page.getByTestId("password-input").fill("secret123");
// Text selector
await page.getByText("Submit").click();
// Basic assertion
await expect(page.getByTestId("submit-btn")).toBeVisible();
});
Obrigado pelo seu feedback!