跳到主要内容

浏览器日志

在运行测试时,浏览器可能会记录您感兴趣或想要断言的重要信息。

当使用WebDriver Bidi(WebdriverIO默认的浏览器自动化方式)时,您可以订阅来自浏览器的事件。对于日志事件,您需要监听log.entryAdded',例如:

await browser.sessionSubscribe({ events: ['log.entryAdded'] })

/**
* returns: {"type":"console","method":"log","realm":null,"args":[{"type":"string","value":"Hello Bidi"}],"level":"info","text":"Hello Bidi","timestamp":1657282076037}
*/
browser.on('log.entryAdded', (entryAdded) => console.log('received %s', entryAdded))

在测试中,您可以将日志事件推送到数组中,并在操作完成后断言该数组,例如:

import type { local } from 'webdriver'

describe('should log when doing a certain action', () => {
const logs: string[] = []

function logEvents (event: local.LogEntry) {
logs.push(event.text) // add log message to the array
}

before(async () => {
await browser.sessionSubscribe({ events: ['log.entryAdded'] })
browser.on('log.entryAdded', logEvents)
})

it('should trigger the console event', () => {
// trigger the browser send a message to the console
...

// assert if log was captured
expect(logs).toContain('Hello Bidi')
})

// clean up listener afterwards
after(() => {
browser.off('log.entryAdded', logEvents)
})
})

请注意,您可以使用此方法检索错误消息并验证您的应用程序是否遇到任何错误。

Welcome! How can I help?

WebdriverIO AI Copilot