lecture 3 of 160 completed

Managing the browser session

Starting and quitting a browser per test is your job in Selenium. Doing it wrong leaks browsers and blocks the machine.

In Selenium you create the browser yourself. That means you also have to close it, and this is where real damage happens.

Look at this test:

it('creates a contact', async function () {
  const driver = await new Builder().forBrowser('chrome').build();
  await driver.get('/');
  // ... test steps ...
  await driver.quit();
});

It looks correct. It is not. If any line in the middle fails, the test throws and driver.quit() never runs. The browser stays open forever.

Once, on a shared build machine, a broken test left a Chrome process behind on every run. After two days, the machine had over 200 Chrome processes and stopped responding. The failing test itself was a two-minute fix. Finding out why the machine was dying took a day.

The fix is to close the browser in a hook that always runs, no matter how the test ended:

describe('Contacts', function () {
  let driver;

  beforeEach(async function () {
    driver = await new Builder().forBrowser('chrome').build();
    await driver.get('/');
  });

  afterEach(async function () {
    await driver.quit();
  });

  it('creates a contact', async function () {
    // ... test steps ...
  });
});

afterEach runs whether the test passed, failed, or threw an error. That is the guarantee you need.

Two related points that come up in interviews.

close() and quit() are different. close() closes the current window. quit() ends the whole session and all its windows. In teardown you almost always want quit().

A fresh browser per test is the safe default. It is slower, but each test starts clean: no cookies, no leftover login, no state from the last test. If your suite is slow, fix the slow parts first. Sharing one browser across tests brings back all the dependency problems you have been avoiding.

Remember this: create the browser in beforeEach, and quit it in afterEach, always.

Reference: Driver sessions.