モックオブジェクト
モックオブジェクトは、ネットワークモックを表すオブジェクトであり、指定されたurlとfilterOptionsに一致するリクエストに関する情報を格納しています。mockコマンドを使用して取得できます。
mockコマンドを使用するには、Chrome DevToolsプロトコルのサポートが必要です。このサポートは、Chromiumベースのブラウザでローカルにテストを実行する場合、またはSelenium Grid v4以降を使用する場合に提供されます。このコマンドは、クラウドで自動テストを実行する際には**使用できません**。自動化プロトコルセクションで詳細をご覧ください。
WebdriverIOでのリクエストとレスポンスのモックについて詳しくは、Mocks and Spiesガイドをご覧ください。
プロパティ
モックオブジェクトには、次のプロパティが含まれています。
| 名前 | 型 | 詳細 | 
|---|---|---|
| url | 文字列 | mockコマンドに渡されたURL | 
| filterOptions | オブジェクト | mockコマンドに渡されたリソースフィルタオプション | 
| ブラウザ | オブジェクト | モックオブジェクトを取得するために使用されるブラウザオブジェクト。 | 
| calls | Object[] | 一致するブラウザリクエストに関する情報。 url、method、headers、initialPriority、referrerPolic、statusCode、responseHeaders、bodyなどのプロパティが含まれます。 | 
メソッド
モックオブジェクトは、mockセクションにリストされているさまざまなコマンドを提供しており、ユーザーはこれを使用してリクエストまたはレスポンスの動作を変更できます。
イベント
モックオブジェクトはEventEmitterであり、いくつかのイベントがユースケースのために発行されます。
イベントのリストを以下に示します。
request
モックパターンに一致するネットワークリクエストの起動時に発行されるイベント。リクエストはイベントコールバックで渡されます。
リクエストインターフェース
interface RequestEvent {
    requestId: number
    request: Matches
    responseStatusCode: number
    responseHeaders: Record<string, string>
}
overwrite
ネットワークレスポンスがrespondまたはrespondOnceで上書きされたときに発行されるイベント。レスポンスはイベントコールバックで渡されます。
レスポンスインターフェース
interface OverwriteEvent {
    requestId: number
    responseCode: number
    responseHeaders: Record<string, string>
    body?: string | Record<string, any>
}
fail
ネットワークリクエストがabortまたはabortOnceで中断されたときに発行されるイベント。失敗はイベントコールバックで渡されます。
失敗インターフェース
interface FailEvent {
    requestId: number
    errorReason: Protocol.Network.ErrorReason
}
match
新しい一致が追加されたとき、continueまたはoverwriteの前に発行されるイベント。一致はイベントコールバックで渡されます。
一致インターフェース
interface MatchEvent {
    url: string // Request URL (without fragment).
    urlFragment?: string // Fragment of the requested URL starting with hash, if present.
    method: string // HTTP request method.
    headers: Record<string, string> // HTTP request headers.
    postData?: string // HTTP POST request data.
    hasPostData?: boolean // True when the request has POST data.
    mixedContentType?: MixedContentType // The mixed content export type of the request.
    initialPriority: ResourcePriority // Priority of the resource request at the time request is sent.
    referrerPolicy: ReferrerPolicy // The referrer policy of the request, as defined in https://www.w3.org/TR/referrer-policy/
    isLinkPreload?: boolean // Whether is loaded via link preload.
    body: string | Buffer | JsonCompatible // Body response of actual resource.
    responseHeaders: Record<string, string> // HTTP response headers.
    statusCode: number // HTTP response status code.
    mockedResponse?: string | Buffer // If mock, emitting the event, also modified it's response.
}
continue
ネットワークレスポンスが上書きも中断もされていない場合、またはレスポンスが別のモックによって既に送信されている場合に発行されるイベント。requestIdはイベントコールバックで渡されます。
例
保留中のリクエスト数の取得
let pendingRequests = 0
const mock = await browser.mock('**') // it is important to match all requests otherwise, the resulting value can be very confusing.
mock.on('request', ({request}) => {
    pendingRequests++
    console.log(`matched request to ${request.url}, pending ${pendingRequests} requests`)
})
mock.on('match', ({url}) => {
    pendingRequests--
    console.log(`resolved request to ${url}, pending ${pendingRequests} requests`)
})
404ネットワークエラー発生時のエラーの発生
browser.addCommand('loadPageWithout404', (url, {selector, predicate}) => new Promise(async (resolve, reject) => {
    const mock = await this.mock('**')
    mock.on('match', ({url, statusCode}) => {
        if (statusCode === 404) {
            reject(new Error(`request to ${url} failed with "Not Found"`))
        }
    })
    await this.url(url).catch(reject)
    // waiting here, because some requests can still be pending
    if (selector) {
        await this.$(selector).waitForExist().catch(reject)
    }
    if (predicate) {
        await this.waitUntil(predicate).catch(reject)
    }
    resolve()
}))
await browser.loadPageWithout404(browser, 'some/url', { selector: 'main' })
モックレスポンス値が使用されたかどうかを確認する
const firstMock = await browser.mock('**/foo/**')
const secondMock = await browser.mock('**/foo/bar/**')
firstMock.respondOnce({id: 3, title: 'three'})
secondMock.respond({id: 4, title: 'four'})
firstMock.on('overwrite', () => {
    // triggers for first request to '**/foo/**'
}).on('continue', () => {
    // triggers for rest requests to '**/foo/**'
})
secondMock.on('continue', () => {
    // triggers for first request to '**/foo/bar/**'
}).on('overwrite', () => {
    // triggers for rest requests to '**/foo/bar/**'
})
この例では、firstMockが最初に定義されており、1つのrespondOnce呼び出しがあるため、secondMockのレスポンス値は最初のリクエストには使用されませんが、残りのリクエストには使用されます。