0

我正在尝试使用量角器测试套件名称设置浏览器名称。因为我正在使用诱惑记者进行测试报告。但问题是我一直在获取浏览器名称“未定义”。到目前为止,我已经在异步方法中实现了浏览器名称,我想在 suitstarted 中使用该方法。suitstarted 方法是同步的。我无法将西装设置为异步。这样我怎么能等待suitstarted方法并在suit.fullname之后获取浏览器名称。从过去三天开始,我真的被这个问题所困扰,因此我对 Javascript 非常陌生。

这是我的代码

    require('protractor/built/logger').Logger.logLevel = 3;

    exports.config = {

        sync: false,
        multiCapabilities:[
            {
                'browserName' : 'chrome',
                'chromeOptions': { 'args' : ['--disable-extensions']},
                'shardTestFiles': true,
                'maxInstances': 1,
                'unexpectedAlertBehaviour' : 'accept'
            },
            {
                'browserName' : 'firefox',
            },
            {
                'browserName': 'internet explorer',
                'se:ieOptions': {
                    ignoreProtectedModeSettings: true,
                    'ie.ensureCleanSession': true,
                }
            },

            ],

        jvmArgs: ['-Dwebdriver.ie.driver=./node_modules/webdriver-manager/selenium/IEDriverServer3.141.0.exe'],
        directConnect: true,    
        baseUrl: 'http://localhost:4200/',
        framework: 'jasmine',
        jasmineNodeOpts: {
            isVerbose: true,
            showColors: true,
            defaultTimeoutInterval: 1500000
        },
        useAllAngular2AppRoots: true,
        beforeLaunch: function() {

        },
        onPrepare: function() {



            // ------------------------------------------------------
            var Allure = require('allure-js-commons');
            var path = require('path');
            var allure = new Allure();

            var AllureReporter = function CustomJasmine2AllureReporter(userDefinedConfig, allureReporter) {
                var Status = {PASSED: 'passed', FAILED: 'failed', BROKEN: 'broken', PENDING: 'pending'};
                this.allure = allureReporter || allure;
                this.configure = function(userDefinedConfig) {
                    var pluginConfig = {};
                    userDefinedConfig = userDefinedConfig || {};
                    pluginConfig.resultsDir = userDefinedConfig.resultsDir || 'allure-results';
                    pluginConfig.basePath = userDefinedConfig.basePath || '.';
                    var outDir = path.resolve(pluginConfig.basePath, pluginConfig.resultsDir);
                    this.allure.setOptions({targetDir: outDir});
                };
                this.configure(userDefinedConfig);

                var browserNameforSuit;

已编辑

                this.suiteStarted = function(suite) {
                   var capsPromise = browser.getCapabilities();
                    capsPromise.then(function (caps) {
                   browserNameforSuit = caps.get('browserName');
                    console.log(browserNameforSuit)
                  this.allure.startSuite(suite.fullName);
                  console.log(suite.fullName);
            })
        };
                };

                this.suiteDone = function() {
                    this.allure.endSuite();
                };
                this.specStarted = function(spec) {
                    this.allure.startCase(spec.description);
                };
                this.specDone = function(spec) {
                    var status = this._getTestcaseStatus(spec.status);
                    var errorInfo = this._getTestcaseError(spec);
                    this.allure.endCase(status, errorInfo);
                };
                this._getTestcaseStatus = function(status) {
                    if (status === 'disabled' || status === 'pending') {
                        return Status.PENDING;
                    } else if (status === 'passed') {
                        return Status.PASSED;
                    } else {
                        return Status.FAILED;
                    }
                };
                this._getTestcaseError = function(result) {
                    if (result.status === 'disabled') {
                        return {
                            message: 'This test was ignored',
                            stack: ''
                        };
                    } else if (result.status === 'pending') {
                        return {
                            message: result.pendingReason,
                            stack: ''
                        };
                    }
                    var failure = result.failedExpectations ? result.failedExpectations[0] : null;
                    if (failure) {
                        return {
                            message: failure.message,
                            stack: failure.stack
                        };
                    }
                };

            }
            // ------------------------------------------------------

            var Runtime = require('allure-js-commons/runtime');
            let gallure = new Runtime(allure);

            browser.manage().window().maximize();
            require('ts-node').register({
                project: 'e2e/tsconfig.json'
            });

            jasmine.getEnv().addReporter(new AllureReporter ({
                resultsDir: 'allure-results'
            }));

            jasmine.getEnv().addReporter(reporter);

            jasmine.getEnv().afterEach(function (done) {
                    browser.takeScreenshot().then(function (png) {
                        gallure.createAttachment('Screenshot', function () {
                            return new Buffer(png, 'base64')
                        },'image/png')();
                        done();
                    })
            });

        }
    };

引诱的 index.js 是

'use strict';
var assign = require('object-assign'),
    Suite = require('./beans/suite'),
    Test = require('./beans/test'),
    Step = require('./beans/step'),
    Attachment = require('./beans/attachment'),
    util = require('./util'),
    writer = require('./writer');

function Allure() {
    this.suites = [];
    this.options = {
        targetDir: 'allure-results'
    };
}
Allure.prototype.setOptions = function(options) {
    assign(this.options, options);
};

Allure.prototype.getCurrentSuite = function() {
    return this.suites[0];
};

Allure.prototype.getCurrentTest = function() {
    return this.getCurrentSuite().currentTest;
};

Allure.prototype.startSuite = function(suiteName, timestamp) {
    this.suites.unshift(new Suite(suiteName,timestamp));
};

Allure.prototype.endSuite = function(timestamp) {
    var suite = this.getCurrentSuite();
    suite.end(timestamp);
    if(suite.hasTests()) {
        writer.writeSuite(this.options.targetDir, suite);
    }
    this.suites.shift();
};

// other methods
module.exports = Allure;

而 Suit.js 是

function Suite(name, timestamp){
    this.name = name;
    this.start = timestamp || Date.now();
    this.testcases = [];
}
Suite.prototype.end = function(timestamp) {
    this.stop = timestamp || Date.now();
};

Suite.prototype.hasTests = function() {
    return this.testcases.length > 0;
};

Suite.prototype.addTest = function(test) {
    this.testcases.push(test);
};

Suite.prototype.toXML = function() {
    var result = {
        '@': {
            'xmlns:ns2' : 'urn:model.allure.qatools.yandex.ru',
            start: this.start
        },
        name: this.name,
        title: this.name,
        'test-cases': {
            'test-case': this.testcases.map(function(testcase) {
                return testcase.toXML();
            })
        }
    };


    if(this.stop) {
        result['@'].stop = this.stop;
    }

    return result;
};

module.exports = Suite;

如何在 suit.fullname 的末尾设置 browserName。有没有其他方法可以做到这一点。

错误

  Test Suites & Specs:

   1. 0030 Test for correct login

 No specs found
 Finished in 0.017 seconds

  An error was thrown in an afterAll
  AfterAll TypeError: Cannot read property 'end' of undefined


 >> Done!


  Summary:

 Finished in 0.017 seconds

 chrome
 [13:23:03] E/launcher - Cannot read property 'startSuite' of undefined
 [13:23:03] E/launcher - TypeError: Cannot read property 'startSuite' of 
 undefined
  at C:\Users\mnowshin\projects\beck-hb\hb-frontend\protractor.mn.conf.js:130:18
  at ManagedPromise.invokeCallback_ (\node_modules\selenium-webdriver\lib\promise.js:1376:14)
  at TaskQueue.execute_ (\node_modules\selenium-webdriver\lib\promise.js:3084:14)
  at TaskQueue.executeNext_ (\node_modules\selenium-webdriver\lib\promise.js:3067:27)
  at asyncRun (\node_modules\selenium-webdriver\lib\promise.js:2927:27)
  at \node_modules\selenium-webdriver\lib\promise.js:668:7
  at process.internalTickCallback (internal/process/next_tick.js:77:7)
  [13:23:03] E/launcher - Process exited with error code 199

  Process finished with exit code 199
4

1 回答 1

0

所以我不使用 allure,但我可以向您展示如何获取浏览器名称,然后您可以尝试申请您的案例。

尝试从这里改变:

var browserNameforSuit;
  let bName = (async () => {
      try {
           browserNameforSuit = (await browser.getCapabilities()).get('browserName');
           return browserNameforSuit;
      } catch (err) {
           return "Error or smth"
      }
      })();

对此:

var capsPromise = browser.getCapabilities();
var browserNameforSuit;

 capsPromise.then(function (caps) {
   browserNameforSuit = caps.get('browserName');
   //if you need you can return the result to a var in order to user somewhere else
 });

这是我的 conf.js 中的 onComplete

onComplete: function() 
{
var browserName, browserVersion;
var capsPromise = browser.getCapabilities();

capsPromise.then(function (caps) {
  browserName = caps.get('browserName');
  browserVersion = caps.get('version');
  platform = caps.get('platform');

//here I prepare the testConfig adding what I need//

//here I get the xml with the test results and create an html
new HTMLReport().from('./execution_results/reports/xml/xmlresults.xml', testConfig);
});//End Of capsPromise
},

希望能帮助到你!

于 2019-01-15T11:08:38.347 回答