Перейти до основного вмісту

Об'єкт Browser

Успадковується від: EventEmitter

Об’єкт браузера – це екземпляр сеансу, який ви використовуєте для керування браузером або мобільним пристроєм. Якщо ви використовуєте засіб виконання тестів WebdriverIO, ви можете отримати доступ до екземпляра Browser через глобальні змінні browser або driver або імпортувати його з пакунка @wdio/globals. Якщо ви використовуєте WebdriverIO в автономному режимі, екземпляр Browser повертається методом remote.

Сеанс ініціалізується виконавцем тесту. Те саме стосується завершення сеансу. Це також виконується процесом виконання тестів.

Властивості

Об’єкт браузера має такі властивості:

НазваТипОпис
capabilitiesObjectAssigned capabilities from the remote server.
Example:
{
acceptInsecureCerts: false,
browserName: 'chrome',
browserVersion: '105.0.5195.125',
chrome: {
chromedriverVersion: '105.0.5195.52',
userDataDir: '/var/folders/3_/pzc_f56j15vbd9z3r0j050sh0000gn/T/.com.google.Chrome.76HD3S'
},
'goog:chromeOptions': { debuggerAddress: 'localhost:64679' },
networkConnectionEnabled: false,
pageLoadStrategy: 'normal',
platformName: 'mac os x',
proxy: {},
setWindowRect: true,
strictFileInteractability: false,
timeouts: { implicit: 0, pageLoad: 300000, script: 30000 },
unhandledPromptBehavior: 'dismiss and notify',
'webauthn:extension:credBlob': true,
'webauthn:extension:largeBlob': true,
'webauthn:virtualAuthenticators': true
}
requestedCapabilitiesObjectПараметри, що були надіслані на віддалений сервер.
Приклад:
{ browserName: 'chrome' }
sessionIdStringІдентифікатор сеансу, призначений з віддаленого сервера.
optionsObjectWDIO параметри які використовувались для створення об’єкту браузера. Подивитися більше про способи запуску.
commandListString[]Список команд, зареєстрованих в екземплярі браузера
isW3CBooleanIndicates if this is a W3C session
isChromeBooleanIndicates if this Chrome instance
isFirefoxBooleanIndicates if this Firefox instance
isBidiBooleanIndicates if this session uses Bidi
isSauceBooleanIndicates if this session is Running on Sauce Labs
isMacAppBooleanIndicates if this session is Running for a native Mac App
isWindowsAppBooleanIndicates if this session is Running for a native Windows App
isMobileBooleanВказує на мобільний сеанс. Подивіться більше про мобільні прапорці.
isIOSBooleanВказує на сеанс iOS. Подивіться більше про мобільні прапорці.
isAndroidBooleanВказує на сеанс Android. Подивіться більше про мобільні прапорці.
isNativeContextBooleanIndicates if the mobile is in the NATIVE_APP context. See more under Mobile Flags.
mobileContextstringThe will provide the current context the driver is in, for example NATIVE_APP, WEBVIEW_<packageName> for Android or WEBVIEW_<pid> for iOS. It will save an extra WebDriver to driver.getContext(). See more under Mobile Flags.

Методи

На основі серверної частини автоматизації, яка використовується для вашого сеансу, WebdriverIO визначає, які команди протоколів будуть приєднані до об’єкта браузера. Наприклад, якщо ви запускаєте автоматизований сеанс у Chrome, ви матимете доступ до спеціальних команд Chromium, таких як elementHover, але не до жодної з команд Appium.

Крім того, WebdriverIO надає набір зручних методів, які рекомендується використовувати для взаємодії з браузером або елементами на сторінці.

На додаток до цього доступні такі команди:

НазваПараметриОпис
addCommand- commandName (Type: String)
- fn (Type: Function)
- attachToElement (Type: boolean)
Дозволяє додати спеціальні команди, які можна викликати з об’єкта браузера для цілей композиції. Докладніше читайте в розділі Клієнтські Команди.
overwriteCommand- commandName (Type: String)
- fn (Type: Function)
- attachToElement (Type: boolean)
Дозволяє перезаписувати будь-яку команду браузера клієнтською функціональністю. Використовуйте обережно, оскільки це може заплутати користувачів фреймворку. Докладніше читайте в розділі Клієнтські Команди.
addLocatorStrategy- strategyName (Type: String)
- fn (Type: Function)
Allows to define a custom selector strategy, read more in the Selectors guide.

Примітки

Мобільні Прапорці

Якщо вам потрібно налаштувати свій тест залежно від того, чи працює ваш сеанс на мобільному пристрої, ви можете використати мобільні прапорці, щоб перевірити це.

Наприклад, із цією конфігурацією:

// wdio.conf.js
export const config = {
// ...
capabilities: \\{
platformName: 'iOS',
app: 'net.company.SafariLauncher',
udid: '123123123123abc',
deviceName: 'iPhone',
// ...
}
// ...
}

Ви зможете отримати доступ до таких прапорців у своєму тесті:

// Note: `driver` is the equivalent to the `browser` object but semantically more correct
// you can choose which global variable you want to use
console.log(driver.isMobile) // outputs: true
console.log(driver.isIOS) // outputs: true
console.log(driver.isAndroid) // outputs: false

Це може бути корисним, якщо, наприклад, ви хочете визначити селектори у своїх об’єктах сторінки на основі типу пристрою, як це:

// mypageobject.page.js
import Page from './page'

class LoginPage extends Page {
// ...
get username() {
const selectorAndroid = 'new UiSelector().text("Cancel").className("android.widget.Button")'
const selectorIOS = 'UIATarget.localTarget().frontMostApp().mainWindow().buttons()[0]'
const selectorType = driver.isAndroid ? 'android' : 'ios'
const selector = driver.isAndroid ? selectorAndroid : selectorIOS
return $(`${selectorType}=${selector}`)
}
// ...
}

Ви також можете використовувати ці прапорці для запуску лише певних тестів для певних типів пристроїв:

// mytest.e2e.js
describe('my test', () => {
// ...
// only run test with Android devices
if (driver.isAndroid) {
it('tests something only for Android', () => {
// ...
})
}
// ...
})

Події

Об’єкт браузера є також і об'єктом EventEmitter, і деякі подій викликатимуться залежно від використання.

Ось список подій. Майте на увазі, що це ще не повний список доступних подій. Не соромтеся робити свій внесок в оновлення документа, додаючи тут описи інших подій.

request.start

This event is fired before a WebDriver request is sent to the driver. It contains information about the request and its payload.

browser.on('request.start', (ev: RequestInit) => {
// ...
})

request.end

This event is fired once the request to the driver received a response. The event object either contains the response body as result or an error if the WebDriver command failed.

browser.on('request.end', (ev: { result: unknown, error?: Error }) => {
// ...
})

request.retry

The retry event can notify you when WebdriverIO attempts to retry running the command, e.g. due to a network issue. It contains information about the error that caused the retry and the amount of retries already done.

browser.on('request.retry', (ev: { error: Error, retryCount: number }) => {
// ...
})

command

This event is emitted whenever WebdriverIO sends a WebDriver Classic command. It contains the following information:

  • command: the command name, e.g. navigateTo
  • method: the HTTP method used to send the command request, e.g. POST
  • endpoint: the command endpoint, e.g. /session/fc8dbda381a8bea36a225bd5fd0c069b/url
  • body: the command payload, e.g. { url: 'https://webdriver.io' }

result

This event is emitted whenever WebdriverIO receives a result of a WebDriver Classic command. It contains the same information as the command event with the addition of the following information:

  • result: the command result

bidiCommand

This event is emitted whenever WebdriverIO sends a WebDriver Bidi command to the browser driver. It contains information about:

  • method: WebDriver Bidi command method
  • params: associated command parameter (see API)

bidiResult

In case of a successful command execution, the event payload will be:

  • type: success
  • id: the command id
  • result: the command result (see API)

In case of a command error, the event payload will be:

  • type: error
  • id: the command id
  • error: the error code, e.g. invalid argument
  • message: details about the error
  • stacktrace: a stack trace

request.start

This event is fired before a WebDriver request is sent to the driver. It contains information about the request and its payload.

browser.on('request.start', (ev: RequestInit) => {
// ...
})

request.end

This event is fired once the request to the driver received a response. The event object either contains the response body as result or an error if the WebDriver command failed.

browser.on('request.end', (ev: { result: unknown, error?: Error }) => {
// ...
})

request.retry

The retry event can notify you when WebdriverIO attempts to retry running the command, e.g. due to a network issue. It contains information about the error that caused the retry and the amount of retries already done.

browser.on('request.retry', (ev: { error: Error, retryCount: number }) => {
// ...
})

request.performance

Це подія для відстежування операцій на рівні WebDriver протоколу. Кожного разу, коли WebdriverIO надсилає запит на WebDriver сервер, цю подію буде викликано з параметрами:

  • durationMillisecond: тривалість запиту в мілісекундах.
  • error: об’єкт помилки, якщо запит провалився.
  • request: об'єкт запиту, де можна знайти адресу, метод, заголовки тощо.
  • retryCount: кількість спроб, якщо дорівнює 0, запит був першою спробою. Він збільшиться, коли WebDriverIO повторить спробу під капотом.
  • success: логічне значення, що вказує на те чи було виконано запит. Якщо дорівнює false, властивість error також буде присутня.

Приклад події:

Object {
"durationMillisecond": 0.01770925521850586,
"error": [Error: Timeout],
"request": Object { ... },
"retryCount": 0,
"success": false,
},

Клієнтські Команди

Ви можете додати власні команди до об'єкта браузера, щоб абстрагувати набори команд які часто використовуються. Ознайомтеся з нашим розділом про Користувацькі Команди, щоб дізнатися більше.

Welcome! How can I help?

WebdriverIO AI Copilot