[英]Jest Run All Tests(include only/skip) in CI
在開發過程中,我們偶爾會使用skip
或only
來調試特定的測試或測試套件。 一不小心,我們可能會忘記還原案例並推送代碼以進行 PR。 我正在尋找一種方法來檢測或自動運行所有測試,即使是在我們的 CI 管道中skip
和only
測試(使用 Github 操作)。 它可以是以下任何一種情況。
skip
或only
測試時,測試失敗。skip
和only
運行所有測試。非常感謝任何幫助。
對於問題的第二部分,我想出了一個解決方案,即運行所有測試,即使是skip
和only
。 我不認為這是一個優雅的解決方案,但它有效並且易於實施。
首先,如果你使用 jest bellow 27.x 版本,你需要將測試運行器更改為jest-circus 。 我們需要它,以便我們的自定義測試環境將使用handleTestEvent
function 來監視setup
事件。 為此,請使用npm i jest-circus
安裝jest-circus
circus,然后在您的jest.config.js
中設置testRunner屬性:
//jest.config.js
module.exports = {
testRunner: 'jest-circus/runner',
...
}
從 Jest 27.0 開始,他們將默認測試運行程序更改為jest-circus
,因此如果您有此版本或更高版本,則可以跳過此步驟。
然后你必須編寫自定義測試環境。 我建議基於jsdom
編寫它,例如我們還可以在測試等中訪問window
object。為此,請在終端npm i jest-environment-jsdom
,然后像這樣創建自定義環境:
//custom-jsdom-environment.js
const JsDomEnvironment = require('jest-environment-jsdom')
class CustomJsDomEnvironment extends JsDomEnvironment {
async handleTestEvent(event, state) {
if(process.env.IS_CI === 'true' && event.name === 'setup') {
this.global.describe.only = this.global.describe
this.global.describe.skip = this.global.describe
this.global.fdescribe = this.global.describe
this.global.xdescribe = this.global.describe
this.global.it.only = this.global.it
this.global.it.skip = this.global.it
this.global.fit = this.global.it
this.global.xit = this.global.it
this.global.test.only = this.global.test
this.global.test.skip = this.global.test
this.global.ftest = this.global.test
this.global.xtest = this.global.test
}
}
}
module.exports = CustomJsDomEnvironment
並告知jest
正確使用它:
//jest.config.js
module.exports = {
testRunner: 'jest-circus/runner',
testEnvironment: 'path/to/custom/jsdom/environment.js',
...
}
然后你只需要在你的 CI 管道中設置自定義環境值IS_CI
,從現在開始你所有跳過的測試都會運行。
同樣在自定義測試環境中,您可以觀察跳過的測試並在您的跑步者發現跳過/僅時拋出錯誤。 不幸的是,在這個地方拋出錯誤不會導致測試失敗。 您需要找到一種方法使測試之外的測試失敗。
//custom-jsdom-environment.js
const JsDomEnvironment = require('jest-environment-jsdom')
const path = require('path')
class CustomJsDomEnvironment extends JsDomEnvironment {
constructor(config, context) {
super(config, context)
const testPath = context.testPath
this.testFile = path.basename(testPath)
}
async handleTestEvent(event, state) {
if(process.env.IS_CI === 'true' && event.name === 'add_test') {
if(event.mode === 'skip' || event.mode === 'only') {
const msg = `Run ${event.mode} test: '${event.testName}' in ${this.testFile}`
throw new Error(msg)
}
}
}
}
module.exports = CustomJsDomEnvironment
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.