第一次失败后开玩笑停止测试套件 [英] Jest stop test suite after first fail

查看:27
本文介绍了第一次失败后开玩笑停止测试套件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Jest 进行测试.

I am using Jest for testing.

我想要的是,当该测试套件中的测试失败时停止执行当前测试套件.

What I want, is to stop executing the current test suite when a test in that test suite fails.

--bail 选项不是我需要的,因为它会在一个测试套件失败后停止其他测试套件.

The --bail option is not what I need, since it will stop other test suites after one test suite fails.

推荐答案

我做了一些杂事,但它对我有用.

I've made some kludge but it works for me.

stopOnFirstFailed.js:

/**
 * This is a realisation of "stop on first failed" with Jest
 * @type {{globalFailure: boolean}}
 */

module.exports = {
    globalFailure: false
};

// Injects to jasmine.Spec for checking "status === failed"
!function (OriginalSpec) {
    function PatchedSpec(attrs) {
        OriginalSpec.apply(this, arguments);

        if (attrs && attrs.id) {
            let status = undefined;
            Object.defineProperty(this.result, 'status', {
                get: function () {
                    return status;
                },
                set: function (newValue) {
                    if (newValue === 'failed') module.exports.globalFailure = true;
                    status = newValue;
                },
            })
        }
    }

    PatchedSpec.prototype = Object.create(OriginalSpec.prototype, {
        constructor: {
            value: PatchedSpec,
            enumerable: false,
            writable: true,
            configurable: true
        }
    });

    jasmine.Spec = PatchedSpec;
}(jasmine.Spec);

// Injects to "test" function for disabling that tasks
test = ((testOrig) => function () {
    let fn = arguments[1];

    arguments[1] = () => {
        return module.exports.globalFailure ? new Promise((res, rej) => rej('globalFailure is TRUE')) : fn();
    };

    testOrig.apply(this, arguments);
})(test);

在所有测试之前导入该文件(在第一个 test(...) 之前),例如我的 index.test.js:

Imports that file before all tests (before first test(...)), for ex my index.test.js:

require('./core/stopOnFirstFailed'); // before all tests

test(..., ()=>...);
...

当第一个错误发生时,该代码将所有下一个测试failed标记为globalFailure is TRUE.

That code marks all next tests failed with label globalFailure is TRUE when first error happens.

如果您想排除 failing,例如.您可以像这样执行一些清理测试:

If you want to exclude failing, for ex. some cleanup tests you can do like this:

const stopOnFirstFailed = require('../core/stopOnFirstFailed');

describe('some protected group', () => {
    beforeAll(() => {
        stopOnFirstFailed.globalFailure = false
    });
    test(..., ()=>...);
    ...

它从失败中排除整个组.

使用 Node 8.9.1 和 Jest 23.6.0 测试

Tested with Node 8.9.1 and Jest 23.6.0

这篇关于第一次失败后开玩笑停止测试套件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆