0

[Playwright Interview question #24]: Các loại wait khác nhau trong Playwright?

Câu hỏi phỏng vấn #24: How do you handle different types of waits in Playwright?

Trả lời mẫu:

1. Auto-waiting (Default):

// Playwright tự động chờ element:
// - attached to DOM
// - visible
// - stable (not animating)
// - enabled
// - receives events
await page.locator('#button').click();

2. Wait for Selector States:

// Wait for visible
await page.locator('.modal').waitFor({ state: 'visible' });

// Wait for hidden
await page.locator('.spinner').waitFor({ state: 'hidden' });

// Wait for attached/detached
await page.locator('#dynamic').waitFor({ state: 'attached' });

3. Wait for Navigation:

// Wait for navigation to complete
await page.goto('https://example.com');
await page.waitForURL('**/success');

// Wait for page load states
await page.waitForLoadState('load'); // full page load
await page.waitForLoadState('domcontentloaded'); // DOM ready
await page.waitForLoadState('networkidle'); // no network activity

4. Custom Wait Functions:

// Wait for function
await page.waitForFunction(() => {
  return document.querySelector('.counter').innerText === '10';
});

// With polling
await page.waitForFunction(
  () => window.someVariable === true,
  { polling: 100 } // check every 100ms
);

5. Wait with Timeout:

// Custom timeout
await page.locator('.slow-element').waitFor({ 
  timeout: 60000 // 60 seconds
});

// Global timeout
test.setTimeout(120000); // 2 minutes for whole test

6. Conditional Waits:

// Wait for either condition
const result = await Promise.race([
  page.waitForSelector('.success'),
  page.waitForSelector('.error')
]);

💡Tips:

  • Auto-waiting usually sufficient - no explicit waits needed
  • Avoid waitForTimeout() - use condition-based waits
  • Configure default timeout in playwright.config.js
  • Use waitForLoadState sparingly - can slow tests

Lời Kết

Playwright đang trở thành một trong những automation frameworks phổ biến nhất cho web testing. Thông qua series này, hy vọng bạn sẽ:

  • Nắm vững kiến thức từ cơ bản đến nâng cao
  • Tự tin trong các buổi phỏng vấn
  • Áp dụng hiệu quả vào dự án thực tế
  • Trở thành một phần của cộng đồng Playwright Việt Nam năng động

📚 Bắt đầu hành trình của bạn với: Bài 1: Playwright vs Selenium

💬 Có câu hỏi? Tham gia group Facebook của chúng mình!

Theo dõi series để không bỏ lỡ bài viết mới!


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí