メインコンテンツにスキップ

エミュレーション

WebdriverIOでは、emulateコマンドを使用してWeb APIをエミュレートし、特定のブラウザの動作をエミュレートするのに役立つカスタム値を返すことができます。これには、アプリケーションがこれらのAPIを明示的に使用する必要があることに注意してください。

情報

この機能には、ブラウザのWebDriver Bidiサポートが必要です。最近のバージョンのChrome、Edge、およびFirefoxにはこのようなサポートがありますが、Safariはサポートしていません。最新情報については、wpt.fyiを確認してください。さらに、ブラウザを起動するためにクラウドベンダーを使用している場合は、ベンダーがWebDriver Bidiもサポートしていることを確認してください。

テストでWebDriver Bidiを有効にするには、capabilitiesでwebSocketUrl: trueを設定してください。

位置情報

ブラウザの位置情報を特定の地域に変更します。例:

await browser.emulate('geolocation', {
latitude: 52.52,
longitude: 13.39,
accuracy: 100
})
await browser.url('https://www.google.com/maps')
await browser.$('aria/Show Your Location').click()
await browser.pause(5000)
console.log(await browser.getUrl()) // outputs: "https://www.google.com/maps/@52.52,13.39,16z?entry=ttu"

これにより、navigator.geolocation.getCurrentPositionの動作方法がモンキーパッチされ、指定された場所が返されます。

カラースキーム

以下を使用して、ブラウザのデフォルトのカラースキーム設定を変更します。

await browser.emulate('colorScheme', 'light')
await browser.url('https://webdriverio.dokyumento.jp')
const backgroundColor = await browser.$('nav').getCSSProperty('background-color')
console.log(backgroundColor.parsed.hex) // outputs: "#efefef"

await browser.emulate('colorScheme', 'dark')
await browser.url('https://webdriverio.dokyumento.jp')
const backgroundColor = await browser.$('nav').getCSSProperty('background-color')
console.log(backgroundColor.parsed.hex) // outputs: "#000000"

これにより、(prefers-color-scheme: dark)を介してカラースキームをクエリするときのwindow.matchMediaの動作方法がモンキーパッチされます。

ユーザーエージェント

ブラウザのユーザーエージェントを別の文字列に変更します。

await browser.emulate('userAgent', 'Chrome/1.2.3.4 Safari/537.36')

これにより、navigator.userAgentの値が変更されます。ブラウザベンダーがユーザーエージェントを段階的に非推奨にしていることに注意してください。

onLineプロパティ

ブラウザのオンラインステータスを以下のように変更します。

await browser.emulate('onLine', false)

これにより、ブラウザとインターネット間のネットワークトラフィックがオフになることはなく、navigator.onLineの戻り値のみが変更されます。ブラウザのネットワーク機能を変更することに関心がある場合は、throttleNetworkコマンドを参照してください。

クロック

emulateコマンドを使用して、ブラウザのシステムクロックを変更できます。これにより、時間に関連するネイティブのグローバル関数がオーバーライドされ、clock.tick()またはyieldされたクロックオブジェクトを介して同期的に制御できるようになります。これには、次の制御が含まれます。

  • setTimeout
  • clearTimeout
  • setInterval
  • clearInterval
  • Dateオブジェクト

クロックはunixエポック(タイムスタンプ0)で開始されます。つまり、アプリケーションで新しいDateをインスタンス化すると、emulateコマンドに他のオプションを渡さない場合、1970年1月1日の時間が設定されます。

browser.emulate('clock', { ... })を呼び出すと、現在のページと後続のすべてのページのグローバル関数がすぐに上書きされます。例:

const clock = await browser.emulate('clock', { now: new Date(1989, 7, 4) })

console.log(await browser.execute(() => (new Date()).toString()))
// returns "Fri Aug 04 1989 00:00:00 GMT-0700 (Pacific Daylight Time)"

await browser.url('https://webdriverio')
console.log(await browser.execute(() => (new Date()).toString()))
// returns "Fri Aug 04 1989 00:00:00 GMT-0700 (Pacific Daylight Time)"

await clock.restore()

console.log(await browser.execute(() => (new Date()).toString()))
// returns "Thu Aug 01 2024 17:59:59 GMT-0700 (Pacific Daylight Time)"

await browser.url('http://guinea-pig.webdriver.io/pointer.html')
console.log(await browser.execute(() => (new Date()).toString()))
// returns "Thu Aug 01 2024 17:59:59 GMT-0700 (Pacific Daylight Time)"

システム時間を変更するには、setSystemTimeまたはtickを呼び出します。

FakeTimerInstallOptsオブジェクトには、次のプロパティを設定できます。

interface FakeTimerInstallOpts {
// Installs fake timers with the specified unix epoch
// @default: 0
now?: number | Date | undefined;

// An array with names of global methods and APIs to fake. By default, WebdriverIO
// does not replace `nextTick()` and `queueMicrotask()`. For instance,
// `browser.emulate('clock', { toFake: ['setTimeout', 'nextTick'] })` will fake only
// `setTimeout()` and `nextTick()`
toFake?: FakeMethod[] | undefined;

// The maximum number of timers that will be run when calling runAll() (default: 1000)
loopLimit?: number | undefined;

// Tells WebdriverIO to increment mocked time automatically based on the real system
// time shift (e.g. the mocked time will be incremented by 20ms for every 20ms change
// in the real system time)
// @default false
shouldAdvanceTime?: boolean | undefined;

// Relevant only when using with shouldAdvanceTime: true. increment mocked time by
// advanceTimeDelta ms every advanceTimeDelta ms change in the real system time
// @default: 20
advanceTimeDelta?: number | undefined;

// Tells FakeTimers to clear 'native' (i.e. not fake) timers by delegating to their
// respective handlers. These are not cleared by default, leading to potentially
// unexpected behavior if timers existed prior to installing FakeTimers.
// @default: false
shouldClearNativeTimers?: boolean | undefined;
}

デバイス

emulateコマンドでは、ビューポート、デバイススケールファクター、ユーザーエージェントを変更することで、特定のモバイルまたはデスクトップデバイスのエミュレーションもサポートされています。これは決してモバイルテストに使用すべきではありません。デスクトップブラウザエンジンはモバイルブラウザエンジンとは異なるためです。これは、アプリケーションが小さなビューポートサイズに対して特定の動作を提供する場合にのみ使用する必要があります。

たとえば、ユーザーエージェントとビューポートをiPhone 15に切り替えるには、次を実行します。

const restore = await browser.emulate('iPhone 15')
// test your application ...

// reset to original viewport and user agent
await restore()

WebdriverIOは、定義されたすべてのデバイスの固定リストを保持しています。

ようこそ! 何かお手伝いできることはありますか?

WebdriverIO AI Copilot