Set browserName with protractor test suit name

642 Views Asked by At

I am trying to set the browser name with protractor test suite name. Because I am using allure reporter for test report. But the problem is I am getting browser name 'undefined' all the time. So far I have implemented browser name in an asynchronous method and I would like to use that method in suitstarted. the suitstarted method is synchronous. I cannot set suit started to asynchronous. In that way how can I wait suitstarted method and get the browser name after the suit.fullname. I am really stuck with this issue from last three days hence I am very new in Javascript.

Here is my code

    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;

Edited

                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();
                    })
            });

        }
    };

The index.js for Allure is

'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;

And the Suit.js is

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;

How can I set browserName at the end of the suit.fullname. Is there any alternative way to do that.

Error

  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

There are 1 best solutions below

5
On

so I don't work with allure, but I can show you how I get the browser name and then you can try to apply to your case.

Try to change from this:

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

To this:

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
 });

This is the onComplete from my conf.js

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

Hope it helps!