Automated Javascript, Selenium, Mocha and Chai Test Suite
Sure! Below is an example of an automated test suite using Selenium, JavaScript, and the Page Object Model design pattern to validate the functionality of a digital health product. The test suite covers critical features such as user registration, logging in, entering health data, setting goals, and generating progress reports. It also includes positive and negative scenarios to handle different situations. The example assumes you have the necessary setup and dependencies installed, including Node.js, Selenium WebDriver, Mocha, and Chai.
Project Structure
- Create a new project directory and navigate into it.
- Inside the project directory, create the following directories:
pages
: Contains page objects for each page of the application.tests
: Contains test scripts for each feature.data
: Contains test data and configurations.reports
: Contains HTML reports and screenshots.
- Install the required dependencies by running the following command in the project directory:
npm install selenium-webdriver mocha chai
Test Suite Setup
- Open your preferred text editor and create a new file named
test-setup.js
in the project directory. - Add the following code to the
test-setup.js
file:
javascriptconst { Builder, Capabilities } = require('selenium-webdriver');
// Set up WebDriver
const capabilities = Capabilities.chrome();
capabilities.set('chromeOptions', {
args: ['--headless', '--disable-gpu'] // Optional: Run tests in headless mode
});
const driver = new Builder()
.withCapabilities(capabilities)
.build();
// Global test configuration
const baseUrl = 'https://your-health-product.com';
module.exports = {
driver,
baseUrl
};
Page Objects
- Create a new file named
LoginPage.js
inside thepages
directory. - Add the following code to the
LoginPage.js
file:
javascriptconst { By, until } = require('selenium-webdriver');
const { driver, baseUrl } = require('../test-setup');
class LoginPage {
constructor() {
this.usernameInput = By.id('username');
this.passwordInput = By.id('password');
this.loginButton = By.id('login-button');
this.errorMsg = By.id('error-message');
}
async open() {
await driver.get(`${baseUrl}/login`);
await driver.wait(until.elementLocated(this.usernameInput));
}
async login(username, password) {
await driver.findElement(this.usernameInput).sendKeys(username);
await driver.findElement(this.passwordInput).sendKeys(password);
await driver.findElement(this.loginButton).click();
await driver.wait(until.urlIs(`${baseUrl}/dashboard`));
}
async getErrorMessage() {
const element = await driver.findElement(this.errorMsg);
return element.getText();
}
}
module.exports = LoginPage;
- Create similar page object files for other pages of the application (e.g.,
RegistrationPage.js
,DashboardPage.js
, etc.) using the same structure asLoginPage.js
.
Test Scripts
- Create a new file named
registration.test.js
inside thetests
directory. - Add the following code to the
registration.test.js
file:
javascriptconst { expect } = require('chai');
const { driver, baseUrl } = require('../test-setup');
const LoginPage = require('../pages/LoginPage');
describe('User Registration', () => {
let loginPage;
before(async () => {
loginPage = new LoginPage();
await loginPage.open();
});
after(async () => {
await driver.quit();
});
it('should display a success message upon successful registration', async () => {
// Test data
const username = 'testuser';
const password = 'testpassword';
await loginPage.register(username, password);
const successMessage = await loginPage.getSuccessMessage();
expect(successMessage).to.equal('Registration successful!');
});
it('should display an error message when registering with an existing username', async () => {
// Test data
const username = 'existinguser';
const password = 'testpassword';
await loginPage.register(username, password);
const errorMessage = await loginPage.getErrorMessage();
expect(errorMessage).to.equal('Username already exists!');
});
});
- Create similar test script files for other features (e.g.,
login.test.js
,dataEntry.test.js
, etc.) using the same structure asregistration.test.js
.
Running the Test Suite
- Open your terminal or command prompt and navigate to the project directory.
- Run the following command to execute the test suite:css
npx mocha --recursive tests/
Test Reporting
To generate HTML reports and screenshots, you can use the mochawesome
package. Follow these steps to set it up:
Install the
mochawesome
package by running the following command in the project directory:npm install mochawesome
Modify the
test-setup.js
file as follows:
javascriptconst { Builder, Capabilities } = require('selenium-webdriver');
const { after } = require('mocha');
// Set up WebDriver
const capabilities = Capabilities.chrome();
capabilities.set('chromeOptions', {
args: ['--headless', '--disable-gpu'] // Optional: Run tests in headless mode
});
const driver = new Builder()
.withCapabilities(capabilities)
.build();
// Global test configuration
const baseUrl = 'https://your-health-product.com';
// Add Mochawesome reporter
after(() => {
const Mochawesome = require('mochawesome');
new Mochawesome().report();
});
module.exports = {
driver,
baseUrl
};
- Run the test suite again using the same command as before. After the tests complete, a report will be generated in the
reports
directory.
That's it! You now have an automated test suite using Selenium, JavaScript, and the Page Object Model design pattern to validate the functionality of your digital health product. You can extend the suite by adding more test scripts for additional features and scenarios. Remember to update the page objects and test scripts according to your specific application.
Certainly! Here's an example of a JavaScript code snippet that uses Selenium WebDriver, MochaJS, and ChaiJS to automate the testing of a digital health web application. The code covers the test scenarios you mentioned: login functionality, feature search, health data entry, and goal setting.
javascriptconst { Builder, By, Key, until } = require('selenium-webdriver');
const { expect } = require('chai');
describe('Digital Health Web Application', function () {
let driver;
before(async function () {
driver = await new Builder().forBrowser('chrome').build();
});
after(async function () {
await driver.quit();
});
it('should log in successfully', async function () {
// Launch the web application
await driver.get('https://your-health-web-app.com');
// Navigate to the login page
await driver.findElement(By.linkText('Login')).click();
// Enter valid credentials and click login
await driver.findElement(By.id('username')).sendKeys('testuser');
await driver.findElement(By.id('password')).sendKeys('testpassword', Key.RETURN);
// Verify successful login and redirection to the home page
const pageTitle = await driver.getTitle();
expect(pageTitle).to.equal('Home | Digital Health Web App');
});
it('should search for a feature', async function () {
// Search for a specific feature using the search bar
await driver.findElement(By.id('search-bar')).sendKeys('goal tracking', Key.RETURN);
// Verify that the search results display the expected outcome accurately
const searchResults = await driver.findElements(By.className('search-result'));
expect(searchResults.length).to.be.greaterThan(0);
});
it('should enter health data', async function () {
// Add a new entry on calories burnt
await driver.findElement(By.linkText('Dashboard')).click();
await driver.findElement(By.id('add-entry-button')).click();
await driver.findElement(By.id('calories-input')).sendKeys('500', Key.RETURN);
// Verify that the entry is added correctly and appears in the dashboard
const entries = await driver.findElements(By.className('entry'));
expect(entries.length).to.be.greaterThan(0);
});
it('should set a goal', async function () {
// Navigate to the goal setting functionality
await driver.findElement(By.linkText('Goals')).click();
await driver.findElement(By.id('set-goal-button')).click();
// Enter goal steps and details
await driver.findElement(By.id('goal-steps-input')).sendKeys('10000');
await driver.findElement(By.id('goal-details-input')).sendKeys('Walk 10,000 steps daily', Key.RETURN);
// Verify that the goal was successfully created and a confirmation message is displayed
const confirmationMessage = await driver.findElement(By.className('confirmation-message')).getText();
expect(confirmationMessage).to.equal('Goal set successfully!');
});
});
In the above code, we use MochaJS as the test framework to structure the tests and ChaiJS for assertions. Selenium WebDriver is used to interact with web elements, perform actions, and retrieve information from the web application.
To run the tests, ensure you have the necessary dependencies and environment setup. Then, execute the script using a test runner like Mocha. The script assumes that the web application is hosted at 'https://your-health-web-app.com'
. Modify the URL as per your application's address.
Make sure to update the locator strategies (e.g., By.id
, By.linkText
, etc.) as per your application's specific HTML structure.
Remember to handle synchronization issues by using implicit and explicit waits, and handle exceptions appropriately.
Feel free to add additional test cases or functionalities to cover other scenarios and edge cases specific to your digital health web application.