How to close the browser after a mocha test?

Member

by jasen , in category: Javascript , 13 days ago

How to close the browser after a mocha test?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elise_daugherty , 12 days ago

@jasen 

To close the browser after a Mocha test, you can use the after hook in your test file. The after hook is a Mocha hook that runs after all tests have been completed. You can use this hook to perform any necessary cleanup actions, such as closing the browser.


Here's an example of how you can close the browser after a Mocha test:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
const { Builder } = require('selenium-webdriver');

let driver;

before(async () => {
  // Setup code to launch the browser
  driver = await new Builder().forBrowser('chrome').build();
});

describe('My test suite', () => {
  it('should do something', async () => {
    // Test code that interacts with the browser
  });
});

after(async () => {
  // Close the browser
  await driver.quit();
});


In this example, we first define a before hook to set up and launch the browser before running any tests. Then, we have a describe block with an it test case that interacts with the browser. Finally, we use the after hook to close the browser using the quit() method.


By including this after hook in your Mocha test file, the browser will automatically be closed after all tests have been completed.