跳至主要內容

重試不穩定的測試

您可以使用 WebdriverIO 測試執行器重新執行某些測試,這些測試由於網路不穩定或競爭條件等問題而變得不穩定。(但是,如果測試變得不穩定,不建議簡單地增加重新執行率!)

在 Mocha 中重新執行套件

從 Mocha 的第 3 版開始,您可以重新執行整個測試套件(describe 區塊中的所有內容)。如果您使用 Mocha,則應優先使用此重試機制,而不是僅允許您重新執行某些測試區塊(it 區塊中的所有內容)的 WebdriverIO 實作。為了使用 this.retries() 方法,套件區塊 describe 必須使用未綁定的函式 function(){},而不是胖箭頭函式 () => {},如 Mocha 文件中所述。使用 Mocha,您還可以使用 wdio.conf.js 中的 mochaOpts.retries 為所有規格設定重試計數。

以下是一個範例

describe('retries', function () {
// Retry all tests in this suite up to 4 times
this.retries(4)

beforeEach(async () => {
await browser.url('http://www.yahoo.com')
})

it('should succeed on the 3rd try', async function () {
// Specify this test to only retry up to 2 times
this.retries(2)
console.log('run')
await expect($('.foo')).toBeDisplayed()
})
})

在 Jasmine 或 Mocha 中重新執行單一測試

若要重新執行特定測試區塊,您只需在測試區塊函式後套用重新執行的次數作為最後一個參數即可

describe('my flaky app', () => {
/**
* spec that runs max 4 times (1 actual run + 3 reruns)
*/
it('should rerun a test at least 3 times', async function () {
console.log(this.wdioRetries) // returns number of retries
// ...
}, 3)
})

這也適用於鉤子

describe('my flaky app', () => {
/**
* hook that runs max 2 times (1 actual run + 1 rerun)
*/
beforeEach(async () => {
// ...
}, 1)

// ...
})

此重試機制僅允許重試單一鉤子或測試區塊。如果您的測試伴隨著一個用於設定應用程式的鉤子,則不會執行此鉤子。Mocha 提供原生測試重試,可提供此行為,而 Jasmine 則不提供。您可以在 afterTest 鉤子中存取已執行重試的次數。

在 Cucumber 中重新執行

在 Cucumber 中重新執行完整套件

對於 cucumber >= 6,您可以提供 retry 組態選項,以及 retryTagFilter 選用參數,讓所有或某些失敗的案例額外重試,直到成功為止。為了使此功能正常運作,您需要將 scenarioLevelReporter 設定為 true

在 Cucumber 中重新執行步驟定義

若要為特定步驟定義定義重新執行率,只需將重試選項套用至其中,例如

export default function () {
/**
* step definition that runs max 3 times (1 actual run + 2 reruns)
*/
this.Given(/^some step definition$/, { wrapperOptions: { retry: 2 } }, async () => {
// ...
})
// ...
})

重新執行只能在您的步驟定義檔案中定義,而不能在您的功能檔案中定義。

在每個規格檔案的基礎上新增重試

先前,僅提供測試和套件層級的重試,這在大多數情況下都很好。

但是在任何涉及狀態的測試(例如在伺服器或資料庫中),狀態可能會在第一次測試失敗後保持無效。由於它們將從無效狀態開始,因此任何後續的重試都可能沒有通過的機會。

為每個規格檔案建立一個新的 browser 執行個體,這使其成為掛鉤和設定任何其他狀態(伺服器、資料庫)的理想位置。此層級的重試表示整個設定程序將僅被重複,就像它是針對新的規格檔案一樣。

wdio.conf.js
export const config = {
// ...
/**
* The number of times to retry the entire specfile when it fails as a whole
*/
specFileRetries: 1,
/**
* Delay in seconds between the spec file retry attempts
*/
specFileRetriesDelay: 0,
/**
* Retried specfiles are inserted at the beginning of the queue and retried immediately
*/
specFileRetriesDeferred: false
}

多次執行特定測試

這有助於防止在程式碼庫中引入不穩定的測試。透過新增 --repeat cli 選項,它將執行指定的規格或套件 N 次。當使用此 cli 標誌時,還必須指定 --spec--suite 標誌。

當向程式碼庫新增新測試時,尤其是在 CI/CD 程序中,這些測試可能會通過並被合併,但稍後會變得不穩定。這種不穩定可能來自許多因素,例如網路問題、伺服器負載、資料庫大小等等。在您的 CD/CD 程序中使用 --repeat 標誌有助於在將這些不穩定測試合併到主要程式碼庫之前將其捕獲。

一種使用策略是在您的 CI/CD 程序中像常規一樣執行您的測試,但是如果您要引入新測試,則可以使用在 --spec 中指定的新規格以及 --repeat 來執行另一組測試,以便它將新測試執行 x 次。如果測試在其中任何一次失敗,則測試將不會被合併,並且需要查看其失敗的原因。

# This will run the example.e2e.js spec 5 times
npx wdio run ./wdio.conf.js --spec example.e2e.js --repeat 5

歡迎!我能如何協助您?

WebdriverIO AI Copilot