How to run a selenium test in mocha?

Member

by dedrick , in category: Javascript , 4 months ago

How to run a selenium test in mocha?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lizzie , 4 months ago

@dedrick 

To run a Selenium test in Mocha, follow these steps:

  1. Install Mocha and Selenium WebDriver using npm:
1
npm install mocha selenium-webdriver


  1. Create a new file for your test script and import the necessary modules:
1
2
const { Builder, By, Key, until } = require('selenium-webdriver');
const { expect } = require('chai');


  1. Write your test cases using Mocha's describe and it functions:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
describe('Google Search Test', function() {
  let driver;

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

  it('should search for Selenium on Google', async function() {
    await driver.get('https://www.google.com');
    await driver.findElement(By.name('q')).sendKeys('Selenium', Key.RETURN);
    await driver.wait(until.titleIs('Selenium - Google Search'), 1000);
    const title = await driver.getTitle();
    expect(title).to.equal('Selenium - Google Search');
  });

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


  1. Run your Mocha test from the command line:
1
mocha mytest.js


This will launch a Chrome browser, perform the search for "Selenium" on Google, and assert that the title of the search results page is correct.