跳至主要內容

模擬物件

模擬物件是一個代表網路模擬的物件,並包含符合給定 urlfilterOptions 的請求資訊。可以使用 mock 命令接收。

資訊

請注意,使用 mock 命令需要支援 Chrome DevTools 協定。如果您在基於 Chromium 的瀏覽器中於本機執行測試,或使用 Selenium Grid v4 或更高版本,則會提供此支援。在雲端執行自動化測試時,無法使用此命令。在 自動化協定 章節中瞭解更多資訊。

您可以在我們的 模擬與間諜 指南中閱讀更多關於在 WebdriverIO 中模擬請求和回應的資訊。

屬性

模擬物件包含以下屬性

名稱類型詳細資料
url字串傳遞至模擬命令的 url
filterOptions物件傳遞至模擬命令的資源篩選選項
瀏覽器物件用於取得模擬物件的 瀏覽器物件
calls物件[]關於符合瀏覽器請求的資訊,包含諸如 urlmethodheadersinitialPriorityreferrerPolicstatusCoderesponseHeadersbody 等屬性

方法

模擬物件提供 mock 章節中列出的各種命令,這些命令允許使用者修改請求或回應的行為。

事件

模擬物件是 EventEmitter,並為您的使用案例發出幾個事件。

以下是事件清單。

request

當啟動符合模擬模式的網路請求時,會發出此事件。請求會傳遞至事件回呼中。

請求介面

interface RequestEvent {
requestId: number
request: Matches
responseStatusCode: number
responseHeaders: Record<string, string>
}

overwrite

當網路回應被 respondrespondOnce 覆寫時,會發出此事件。回應會傳遞至事件回呼中。

回應介面

interface OverwriteEvent {
requestId: number
responseCode: number
responseHeaders: Record<string, string>
body?: string | Record<string, any>
}

fail

當網路請求被 abortabortOnce 中止時,會發出此事件。失敗會傳遞至事件回呼中。

失敗介面

interface FailEvent {
requestId: number
errorReason: Protocol.Network.ErrorReason
}

match

當新增新的符合項時,會在 continueoverwrite 之前發出此事件。符合項會傳遞至事件回呼中。

符合項介面

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 是第一個定義的,並且有一個 respondOnce 呼叫,因此 secondMock 回應值不會用於第一個請求,但會用於其餘的請求。

歡迎!我可以如何協助您?

WebdriverIO AI Copilot