Search code examples
javascriptselenium-webdriverfirefoxcucumberjs

How can I prevent Selenium Webdriver opening multiple instances of Firefox?


I am writing some automated tests using Selenium Webdriver on Node.js. So far they are working fine, but I have one problem: Whenever I run a test (just 1 test), 4 instances of Firefox open. The test will run and complete in one of the FF windows, but the others will remain open.

Is this something to do with the asynchronous approach?

Would anyone know how I could limit how many instances of FF open when I run a test?

My code is as such:

const { Then, Given, When, After } = require('@cucumber/cucumber');
const assert = require('assert');
const { Builder, By, until, Key } = require('selenium-webdriver');
const firefox = require('selenium-webdriver/firefox');

let options = new firefox.Options();

const driver = new Builder()
    .forBrowser('firefox')
    .setFirefoxOptions(options)
    .build();


Given('I am on a page that needs to be tested', async function () {
    driver.wait(until.elementLocated(By.tagName('h1')));
    await driver.get('https://www.awebsite.com');
});

When('I do the thing', async function() {
   //.....tests, etc

The output I get in console running the test is:

Selenium Manager binary found at /me/automated-testing/node_modules/selenium-webdriver/bin/macos/selenium-manager
Driver path: /me/.cache/selenium/geckodriver/mac-arm64/0.34.0/geckodriver
Browser path: /Applications/Firefox.app/Contents/MacOS/firefox
Driver path: /me/.cache/selenium/geckodriver/mac-arm64/0.34.0/geckodriver
Browser path: /Applications/Firefox.app/Contents/MacOS/firefox
Driver path: /me/.cache/selenium/geckodriver/mac-arm64/0.34.0/geckodriver
Browser path: /Applications/Firefox.app/Contents/MacOS/firefox
Driver path: /me/.cache/selenium/geckodriver/mac-arm64/0.34.0/geckodriver
Browser path: /Applications/Firefox.app/Contents/MacOS/firefox
.....

1 scenario (1 passed)
3 steps (3 passed)
0m04.525s (executing steps: 0m04.517s)

As you can see, FireFox is opened 4 times. I am unsure how to restrict this so only 1 instance opens. Would anyone know how to do this?


Solution

  • This was due to Cucumber JS, not Selenium.

    Cucumber JS amalgamates all your step files into 1 file. So, if you have, say, 4 step files with 4 instances of

    const driver = new Builder()
        .forBrowser('firefox')
        .setFirefoxOptions(options)
        .build();
    

    this will run 4 times and FireFox will open 4 times.

    A work around is to place the builder within the first step of each step file, eg:

    Given('I am on the About page', async function () {
        this.driver = new Builder()
            .forBrowser('firefox')
            .build();
            this.driver.wait(until.elementLocated(By.tagName('h1')));
        await this.driver.get('https://www.some-site.com/about');
    });
    

    Note the inclusion of this now.