在开发过程中,我们偶尔会使用skip或only调试特定的测试或测试套件。一不小心,我们可能会忘记恢复案例并推送 PR 代码。我正在寻找一种方法来检测或自动运行所有测试,甚至是skip我们only的 CI 管道中的测试(使用 Github 操作)。无论是哪种情况都可以,如下所示。
skip当有或测试时测试失败only。skip甚至对和运行所有测试only。非常感谢任何帮助。
我为问题的第二部分提出了一个解决方案,即运行所有测试,甚至为skip和only。我不认为这是一个优雅的解决方案,但它有效并且很容易实现。
首先,如果您使用 jest bellow 27.x 版本,则需要将测试运行器更改为jest-circus 。我们需要它,以便我们的自定义测试环境将使用handleTestEvent函数来监视setup事件。为此,请jest-circus使用 进行安装npm i jest-circus,然后在您jest.config.js设置的testRunner属性中安装:
//jest.config.js
module.exports = {
testRunner: 'jest-circus/runner',
...
}
Run Code Online (Sandbox Code Playgroud)
从 Jest 27.0 开始,他们将默认测试运行程序更改为,jest-circus因此如果您有此版本或更高版本,您可以跳过此步骤。
然后你必须编写自定义测试环境。我建议基于jsdom这样的方式编写它,例如我们还可以访问window测试中的对象等。为此,请在终端中运行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
Run Code Online (Sandbox Code Playgroud)
并告知jest正确使用它:
//jest.config.js
module.exports = {
testRunner: 'jest-circus/runner',
testEnvironment: 'path/to/custom/jsdom/environment.js',
...
}
Run Code Online (Sandbox Code Playgroud)
然后,您只需IS_CI在 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1356 次 |
| 最近记录: |