用量角器测试服名称设置browserName

时间:2019-01-15 09:35:13

标签: javascript async-await protractor settimeout mutablecapabilities

我正在尝试使用量角器测试套件名称设置浏览器名称。因为我正在使用魅力记者进行测试报告。但是问题是我一直在获取浏览器名称“ undefined”。到目前为止,我已经以异步方法实现了浏览器名称,并且我想在suitstarted中使用该方法。 suitstarted方法是同步的。我无法将西装开始设置为异步。这样,我如何等待suitstarted方法并在suite.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();
                    })
            });

        }
    };

Allure的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

1 个答案:

答案 0 :(得分:0)

所以我不会着迷,但是我可以向您展示如何获得浏览器名称,然后您可以尝试将其应用于您的情况。

尝试对此进行更改:

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
},

希望有帮助!