Об'єкт Browser
Успадковується від: EventEmitter
Об’єкт браузера – це екземпляр сеансу, який ви використовуєте для керування браузером або мобільним пристроєм. Якщо ви використовуєте засіб виконання тестів WebdriverIO, ви можете отримати доступ до екземпляра Browser через глобальні змінні browser
або driver
або імпортувати його з пакунка @wdio/globals
. Якщо ви використовуєте WebdriverIO в автономному режимі, екземпляр Browser повертається методом remote
.
Сеанс ініціалізується виконавцем тесту. Те саме стосується завершення сеансу. Це також виконується процесом виконання тестів.
Властивості
Об’єкт браузера має такі властивості:
Назва | Тип | Опис |
---|---|---|
capabilities | Object | Assigned capabilities from the remote server. Example: { |
requestedCapabilities | Object | Параметри, що були надіслані на відд алений сервер. Приклад: { browserName: 'chrome' } |
sessionId | String | Ідентифікатор сеансу, призначений з віддаленого сервера. |
options | Object | WDIO параметри які використовувались для створення об’єкту браузера. Подивитися більше про способи запуску. |
commandList | String[] | Список команд, зареєстрованих в екземплярі браузера |
isW3C | Boolean | Indicates if this is a W3C session |
isChrome | Boolean | Indicates if this Chrome instance |
isFirefox | Boolean | Indicates if this Firefox instance |
isBidi | Boolean | Indicates if this session uses Bidi |
isSauce | Boolean | Indicates if this session is Running on Sauce Labs |
isMacApp | Boolean | Indicates if this session is Running for a native Mac App |
isWindowsApp | Boolean | Indicates if this session is Running for a native Windows App |
isMobile | Boolean | Вказує на мобільний сеанс. Подивіться більше про мобільні прапорці. |
isIOS | Boolean | Вказує на сеанс iOS. Подивіться більше про м обільні прапорці. |
isAndroid | Boolean | Вказує на сеанс Android. Подивіться більше про мобільні прапорці. |
isNativeContext | Boolean | Indicates if the mobile is in the NATIVE_APP context. See more under Mobile Flags. |
mobileContext | string | The 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 methodparams
: associated command parameter (see API)
bidiResult
In case of a successful command execution, the event payload will be:
type
:success
id
: the command idresult
: the command result (see API)
In case of a command error, the event payload will be:
type
:error
id
: the command iderror
: the error code, e.g.invalid argument
message
: details about the errorstacktrace
: 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,
},
Клієнтські Команди
Ви можете додати власні команди до об'єкта браузера, щоб абстрагувати набори команд які часто використовуються. Ознайомтеся з нашим розділом про Користувацькі Команди, щоб дізнатися більше.