Home > database >  I am having issues running selenium tests headless with chrome
I am having issues running selenium tests headless with chrome

Time:05-28

I am using "selenium-webdriver": "4.0.0-alpha.7" with javascript. When I try to run my test cases headless passing in the .withCapabilities . The test just runs with the chrome browser and not headless.

I have a config.js file that looks like this

// filename: lib/config.js
     
    module.exports = {
       baseUrl: process.env.BASE_URL || 'https://www.mycompanyURL.com',
       host: process.env.HOST || 'headless',
        headless: {
          "browserName": process.env.BROWSER_NAME || 'chrome'
          "chromeOptions": {
            "args": ['--headless'],
               },
          },
         localhost: {
              "browserName": process.env.BROWSER_NAME || 'chrome'
              }
          }
        

And I have a driveFactory.js that looks like this

    // filename: DriverFactory.js
    const path = require('path')
    const { Builder } = require('selenium-webdriver')
    
    class DriverFactory {
      constructor(config) {
        this.config = config
      }
    
      _configure() {
        let builder = new Builder()
        switch (this.config.host) {
    
          case 'localhost':
                  builder.withCapabilities(this.config.localhost)
            break
    
          case 'headless':
                    builder.withCapabilities(this.config.headless).
            break
        }
        return builder
      }
  }

module.exports = DriverFactory 




 

Does anyone have any idea why the headless arguments are not being set in the capablitiies?

CodePudding user response:

As of Selenium 4 (and, IIRC, some of the later versions of the Selenium 3 series) vendor-specific arguments have been namespaced, in accordance with the WebDriver Spec.

Arguments now need to be provided to the driver under the goog namespace, eg goog:chromeOptions.

An option

You could replace your config with the following:

        headless: {
          "browserName": process.env.BROWSER_NAME || 'chrome'
          "goog:chromeOptions": {
            "args": ['--headless'],
               },
          },

A better idea

The selenium-webdriver library has built-in options for setting Chrome (and Chromium, for that matter) into headless mode. Doing things this way will mean you don't have to keep track of the argument values needed, and is IMO a bit cleaner.

Just update your driverFactory:

      case "headless":
        builder.withCapabilities(this.config.headless)
            .setChromeOptions(new chrome.Options().headless());
        break;
  • Related