Search code examples
webdriver-iocucumberjs

How can I create a new browser session and delete it on webdriverio?


I'm using an implementation of webdriverio with cucumberjs.

I would like that every scenario I run creates a new browser, and deletes it after the scenario finishes running.

I thought this could be achieved through the use of cucumber hooks

 beforeScenario: async function (world) {
   await browser.newSession(capabilities)
}

afterScenario: async function (world) {
       await browser.deleteSession()
    }

However, this doesn't work, using reloadSession() after the scenarios is not ideal because it reloads the browser after running individual scenarios, which is unnecessary.

I noticed that the test runner creates a new browser object every time is ran, it's there any way I can skip that and create it at the beforeScenario level?


Solution

  • You can handle this by creating an another class like 'DriverFactory', which takes browser name as constructor parameter. Based on this parameter, launch respective browser and return it. In another class, create a static variable like public status driver. Assign above class returned driver object to this variable in your beforeScenario hook in case its value is undefined like:

        beforeScenario: async function (world) {
          if (driver === 'undefined') {
              driver = DriverFactory.launchBrowser("browsername");
    
    }
        }
    

    in this case, on every scenario this block will be executed and checks whether variable is undefined. If Yes, it creates/ launches a new browser instance, else it will not..