Học Playwright tiếng Việt, Cộng đồng Playwright cho người Việt

Vọc Vạch Playwright

[Vọc Playwright] Action

https://playwright.dev/docs/input

Giới thiệu

  • Playwright có thể tương tác với các phần tử dạng input như input, textarea, checkbox và radio button; hay có thể tương tác với select, click chuột, nhập ký tự, bấm phím tắt cũng như tải file lên và focus vào các phần tử.

Text input

  • Sử dụng locator.fill() hoạt động tốt với <input>, <textarea>[contenteditable].
// Text input
await page.getByRole('textbox').fill('Peter');

// Date input
await page.getByLabel('Birth date').fill('2020-02-02');

// Time input
await page.getByLabel('Appointment time').fill('13:15');

// Local datetime input
await page.getByLabel('Local time').fill('2020-03-02T05:15');

Checkbox và radio button

  • Sử dụng locator.setChecked() hoặc locator.check().
  • Phương thức này có thể được sử dụng với các phần tử input[type=checkbox], input[type=radio][role=checkbox].
await page.getByLabel('I agree to the terms above').check();

expect(page.getByLabel('Subscribe to newsletter')).toBeChecked();

await page.getByLabel('XL').check();

Select option

  • Bạn có thể chọn một hoặc nhiều option với locator.selectOption().
  • Có thể chọn theo label, value.
// Chọn theo option label hoặc value
await page.getByLabel('Choose a color').selectOption('blue');

// Chọn theo option label
await page.getByLabel('Choose a color').selectOption({ label: 'Blue' });

// Chọn nhiều value
await page.getByLabel('Choose multiple colors').selectOption(['red', 'green', 'blue']);

Mouse click

  • Khá dễ:
// Nhấp chuột chung
await page.getByRole('button').click();

// Nhấp chuột kép
await page.getByText('Item').dblclick();

// Nhấp chuột phải
await page.getByText('Item').click({ button: 'right' });

// Shift + click
await page.getByText('Item').click({ modifiers: ['Shift'] });

// Ctrl + click or Windows and Linux
// Meta + click on macOS
await page.getByText('Item').click({ modifiers: ['ControlOrMeta'] });

// Hover vào phần tử
await page.getByText('Item').hover();

// Click vào góc trái, trên cùng của phần tử
await page.getByText('Item').click({ position: { x: 0, y: 0 } });
  • Về bản chất thì các method liên quan đến pointer (con trỏ) sẽ chờ trước khi thực hiện hành động:
    • Chờ cho phần tử với bộ chọn được đưa ra nằm trong DOM
    • Chờ cho nó hiển thị, nghĩa là không rỗng, không có display:none, không có visibility:hidden
    • Chờ cho nó ngừng di chuyển, ví dụ, cho đến khi transform CSS kết thúc
    • Scroll phần tử vào trong viewport
    • Chờ cho nó nhận được sự kiện click tại điểm hành động, ví dụ, chờ cho đến khi phần tử không bị che khuất bởi các phần tử khác
    • Thử lại nếu bất cứ điều kiện nào phía trên không thoả mãn.

Force click

  • Đôi khi, bạn vẫn muốn click vào phần tử, dù nó đang bị phần tử khác che đi, bạn có thể dùng force click
await page.getByRole('button').click({ force: true });

Click một cách “máy móc”

  • Về bản chất, việc click vào đâu đó là bạn đang muốn trigger sự kiện click.
  • Bạn có thể trigger bằng cách sử dụng locator.dispatchEvent()
await page.getByRole('button').dispatchEvent('click');

Gõ từng kí tự

  • Nếu bạn muốn gõ từng kí tự như người dùng, bạn có thể dùng locator.pressSequentially()
// Press keys one by one
await page.locator('#area').pressSequentially('Hello World!');

Gõ phím và bấm phím tắt

// Bấm Enter
await page.getByText('Submit').press('Enter');

// Bấm Control + Mũi tên phải
await page.getByRole('textbox').press('Control+ArrowRight');

// Bấm phím $
await page.getByRole('textbox').press('$');
  • locator.press() sẽ focus vào phần tử được chọn và bấm phím một lần duy nhất.
  • Tên phím lấy ở keyboardEvent.key
Backquote, Minus, Equal, Backslash, Backspace, Tab, Delete, Escape,
ArrowDown, End, Enter, Home, Insert, PageDown, PageUp, ArrowRight,
ArrowUp, F1 - F12, Digit0 - Digit9, KeyA - KeyZ, etc.

Upload files

  • Tải file khá đơn giản, dùng hàm setInputFiles():
// Chọn một file
await page.getByLabel('Upload file').setInputFiles(path.join(__dirname, 'myfile.pdf'));

// Chọn nhiều files
await page.getByLabel('Upload files').setInputFiles([
  path.join(__dirname, 'file1.txt'),
  path.join(__dirname, 'file2.txt'),
]);

// Xóa tất cả các files được chọn
await page.getByLabel('Upload file').setInputFiles([]);

// Tạo ra 1 file text và upload
await page.getByLabel('Upload file').setInputFiles({
  name: 'file.txt',
  mimeType: 'text/plain',
  buffer: Buffer.from('this is test')
});
  • Trong trường hợp phần chọn file hiển thị random mà bạn không kiểm soát được, hoặc không trigger được, bạn có thể bắt theo event filechooser
// Start waiting for file chooser before clicking. Note no await.
const fileChooserPromise = page.waitForEvent('filechooser');
await page.getByLabel('Upload file').click();
const fileChooser = await fileChooserPromise;
await fileChooser.setFiles(path.join(__dirname, 'myfile.pdf'));

Focus vào phần tử

  • Dùng hàm locator.focus().
await page.getByLabel('Password').focus();

Drag and drop

  • Bạn có thể thực hiện thao tác kéo và thả với locator.dragTo(). Phương thức này sẽ:

    • Di chuột qua phần tử sẽ được kéo.
    • Nhấn nút chuột trái.
    • Di chuyển chuột đến phần tử sẽ nhận thả.
    • Thả nút chuột trái.
await page.locator('#item-to-be-dragged').dragTo(page.locator('#item-to-drop-at'));

Drag kiểu nông dân

  • Sử dụng các method locator.hover(), mouse.down(), mouse.move()mouse.up() giống như người dùng bình thường.
await page.locator('#item-to-be-dragged').hover();
await page.mouse.down();
await page.locator('#item-to-drop-at').hover();
await page.mouse.up();

Trả lời