Selenium – How to prevent selenium to open a new chrome window on every test run

seleniumselenium-webdriver

So I'm running selenium tests with selenium-webdriver in a react project. Every time I run the tests it opens up a new chrome window, which is extremely irritating, since I end up with a million chrome windows open. Is it possible to force selenium to use the browser window already open?

enter image description here

EDIT:
Here's a simple example of the test code.

const webdriver = require('selenium-webdriver');
const { By, Key } = webdriver

describe('Dashboard page', () => {

  it('renders correctly', async() => {
    var chromeCapabilities = webdriver.Capabilities.chrome();
    var chromeOptions = {
      //'args': ['--headless']
    };
    chromeCapabilities.set('chromeOptions', chromeOptions);
    const driver = new webdriver.Builder().withCapabilities(chromeCapabilities).build();

    await driver.get('http://localhost:3000/dashboard')

    await driver.getTitle().then((title) => {
      expect(title).toEqual("My website | Dashboard")
    })

    await driver.getCurrentUrl().then((url) => {
      expect(url).toEqual("http://localhost:3000/dashboard")
    })
  })
})

Best Answer

If you are using javascript bindings with Jasmine framework then you can try using below code. You can also refer jasmin docs for more details here

beforeEach will run only once for all tests inside a spec.js

Start browser session in beforeEach

afterEach will run once for all tests inside a spec.js

End browser session in AfterEach

 describe('Before Each Spec', function () {
  beforeEach(function () {
  // Create new browser instance once for all spec tests
    var chromeCapabilities = webdriver.Capabilities.chrome();
    var chromeOptions = {
      //'args': ['--headless']
    };
    chromeCapabilities.set('chromeOptions', chromeOptions);
    const driver = new webdriver.Builder().withCapabilities(chromeCapabilities).build();

  });


describe('Test Method 1', function() {
  it('should have a title', function() {
    // TO DO Code
  });
});

describe('Test Method 2', function() {
  it('should have a something to test', function() {
    // TO DO Code
  });
});

describe('After Each Spec', function () {
  afterEach(function () {
  // Destroy browser after all tests finished
   browser.quit(); (or browser.driver.close();)

  });

If you are using java then you can use below annotation which runs only once for complete testng xml or once per testng class e.g. @BeforeSuite or @BeforeClass

@BeforeSuite
public void setUP(){
startSeleniumSession();
}

public void startSeleniumSession(){
WebDriver driver = new ChromeDriver();
}

@Test
public void startTest2(){
driver.get("some url 1");
driver.findElement(By.id("someID")).click()
}


@Test
public void startTest2(){
// this test will run in same browser
driver.get("some url 2");
driver.findElement(By.id("someID")).click()
}

@AfterSuite
public void tearDown(){
driver.quit();
}
Related Topic