跳到主要內容

斷言

WDIO 測試執行器內建斷言函式庫,可讓您對瀏覽器或(網頁)應用程式中的元素進行強大的斷言。它擴充了 Jest Matchers 的功能,並加入了額外為端對端測試最佳化的匹配器,例如:

const $button = await $('button')
await expect($button).toBeDisplayed()

const selectOptions = await $$('form select>option')

// make sure there is at least one option in select
await expect(selectOptions).toHaveChildren({ gte: 1 })

如需完整清單,請參閱 expect API 文件

從 Chai 遷移

Chaiexpect-webdriverio 可以共存,並且只需進行一些微調,即可順利轉換到 expect-webdriverio。如果您已升級到 WebdriverIO v6,那麼預設情況下,您可以直接存取 expect-webdriverio 中的所有斷言。這表示,在任何您使用 expect 的地方,都會呼叫 expect-webdriverio 的斷言。除非您將 injectGlobals 設為 false,或已明確覆寫全域的 expect 以使用 Chai。在這種情況下,您必須明確匯入 expect-webdriverio 套件,才能在需要的地方存取 expect-webdriverio 的任何斷言。

本指南將示範如何從 Chai 遷移(如果 Chai 已在本機覆寫),以及如何從 Chai 遷移(如果 Chai 已在全球覆寫)。

本機

假設 Chai 已在檔案中明確匯入,例如:

// myfile.js - original code
import { expect as expectChai } from 'chai'

describe('Homepage', () => {
it('should assert', async () => {
await browser.url('./')
expectChai(await browser.getUrl()).to.include('/login')
})
})

要遷移此程式碼,請移除 Chai 匯入並使用新的 expect-webdriverio 斷言方法 toHaveUrl 取代

// myfile.js - migrated code
describe('Homepage', () => {
it('should assert', async () => {
await browser.url('./')
await expect(browser).toHaveUrl('/login') // new expect-webdriverio API method https://webdriverio.dev.org.tw/docs/api/expect-webdriverio.html#tohaveurl
});
});

如果想在同一個檔案中使用 Chai 和 expect-webdriverio,您可以保留 Chai 匯入,而 expect 會預設為 expect-webdriverio 斷言,例如:

// myfile.js
import { expect as expectChai } from 'chai'
import { expect as expectWDIO } from '@wdio/globals'

describe('Element', () => {
it('should be displayed', async () => {
const isDisplayed = await $("#element").isDisplayed()
expectChai(isDisplayed).to.equal(true); // Chai assertion
})
});

describe('Other element', () => {
it('should not be displayed', async () => {
await expectWDIO($("#element")).not.toBeDisplayed(); // expect-webdriverio assertion
})
})

全域

假設 expect 已被全域覆寫以使用 Chai。為了使用 expect-webdriverio 斷言,我們需要在「before」hook 中全域設定一個變數,例如:

// wdio.conf.js
before: async () => {
await import('expect-webdriverio');
global.wdioExpect = global.expect;
const chai = await import('chai');
global.expect = chai.expect;
}

現在 Chai 和 expect-webdriverio 可以一起使用。在您的程式碼中,您可以使用 Chai 和 expect-webdriverio 斷言,如下所示,例如:

// myfile.js
describe('Element', () => {
it('should be displayed', async () => {
const isDisplayed = await $("#element").isDisplayed()
expect(isDisplayed).to.equal(true); // Chai assertion
});
});

describe('Other element', () => {
it('should not be displayed', async () => {
await expectWdio($("#element")).not.toBeDisplayed(); // expect-webdriverio assertion
});
});

若要遷移,您可以慢慢將每個 Chai 斷言移至 expect-webdriverio。當所有 Chai 斷言都已在程式碼庫中被取代後,即可刪除「before」hook。然後,全域尋找並取代所有 wdioExpectexpect 的實例,即可完成遷移。

歡迎!我能幫你什麼忙?

WebdriverIO AI Copilot