如何在特定条件下从 Spec 退出 Protractor 测试?

Ram*_*ani 5 exit jasmine protractor e2e-testing

我有一个包含多个规格的套件。每个规范都使用一些库上的代码,这些代码在失败时返回一个被拒绝的承诺。

我可以轻松地catch在规范中拒绝那些被拒绝的承诺。我想知道的是,是否可以让 Protractor 退出该catch函数内的整个套件,因为同一套件中的下一个规范取决于先前规范的成功。

假设我有一个名为的套件testEverything,其中包含这些规格openAppsignIncheckUserlogout。如果openApp失败,所有下一个规范都将由于依赖性而失败。

考虑以下代码openApp

var myLib = require('./myLib.js');

describe('App', function() {

  it('should get opened', function(done) {

    myLib.openApp()
    .then(function() {

      console.log('Successfully opened app');

    })
    .catch(function(error) {

      console.log('Failed opening app');

      if ( error.critical ) {
        // Prevent next specs from running or simply quit test
      }

    })
    .finally(function() {

      done();

    });

  });

});
Run Code Online (Sandbox Code Playgroud)

我将如何退出整个测试?

Ram*_*ani 1

我设法想出了一个解决方法。现在我使用的实际代码要复杂得多,但想法是相同的。

我在量角器的配置文件中添加了一个名为bail. 考虑配置文件顶部的以下代码:

(function () {

  global.bail = false;

})();

exports.config: { ...
Run Code Online (Sandbox Code Playgroud)

上面的代码使用 IIFE(立即调用函数表达式),它bail在量角器global对象上定义变量(在整个测试过程中都可用)。

我还为我需要的 Jasmine 匹配器编写了异步包装器,它将执行一个expect表达式,然后进行比较,并返回一个承诺(使用Q模块)。例子:

var q = require('q');

function check(actual) {

    return {

      sameAs: function(expected) {

          var deferred = q.defer();
          var expectation = {};

          expect(actual).toBe(expected);

          expectation.result = (actual === expected);

          if ( expectation.result ) {

              deferred.resolve(expectation);
          }
          else {
              deferred.reject(expectation);
          }

          return deferred.promise;

      }

    };

}

module.exports = check;
Run Code Online (Sandbox Code Playgroud)

然后在每个规范的末尾,我bail根据规范的进度设置值,这将由这些异步匹配器的承诺确定。考虑以下作为第一个规范:

var check = require('myAsyncWrappers'); // Whatever the path is

describe('Test', function() {

    it('should bail on next spec if expectation fails', function(done) {

        var myValue = 123;

        check(myValue).sameAs('123')
        .then(function(expectation) {

            console.log('Expectation was met'); // Won't happen

        })
        .catch(function(expectation) {

            console.log('Expectation was not met'); // Will happen

            bail = true; // The global variable

        })
        .finally(function() {

            done();

        });

    });

});
Run Code Online (Sandbox Code Playgroud)

最后,在下一个规范开始时,我会检查bail并在必要时返回:

describe('Test', function() {

    it('should be skipped due to bail being true', function(done) {

        if ( bail ) {

            console.log('Skipping spec due to previous failure');

            done();

            return;

        }

        // The rest of spec

    });

});
Run Code Online (Sandbox Code Playgroud)

现在我想提一下,有一个模块叫做,protractor-fail-fast每当期望失败时,它就会对整个测试进行保释。

但就我而言,我需要bail根据失败的期望类型来设置该全局变量。我最终编写了一个库(非常小),将故障区分为关键故障和非关键故障,然后使用它,只有发生关键故障时,规范才会停止。