Home > Web Front-end > JS Tutorial > How to Test Your JavaScript with Selenium WebDriver and Mocha

How to Test Your JavaScript with Selenium WebDriver and Mocha

尊渡假赌尊渡假赌尊渡假赌
Release: 2025-02-16 13:21:09
Original
415 people have browsed it

How to Test Your JavaScript with Selenium WebDriver and Mocha

Core points

  • Mocha.js is a feature-rich JavaScript testing framework based on Node.js, which can be used to write JavaScript functional tests in combination with Selenium WebDriver 3 and NodeJS. This requires familiarity with the basics of NodeJS and JavaScript programming languages.
  • Mocha provides an API for building test code into test suites and test case modules to enable execution and report generation. It supports test suite setup and teardown functions, as well as test case setup and teardown functions.
  • Selenium WebDriver is a library that controls web browsers and simulates user behavior, and can be integrated with MochaJS. It provides a specific language library API called "binding" to control the browser.
  • Async functions used with Mocha need to be handled correctly to avoid unexpected results. This can be done by passing the "done" function to the callback chain or returning a Promise.
  • Other frameworks such as WebdriverIO, Protractor, and CodeseptJS provide wrapper solutions that hide some configurations for users and provide enhanced Promise processing for a better scripting experience.

This article was originally published on TestProject.

If you want to write functional tests in JavaScript, this tutorial provides UI automation engineers with the perfect structured reference material for JavaScript testing using Selenium WebDriver 3, Mocha, and NodeJS.

JavaScript is an ubiquitous web language today that seems to overcome its "notorious" past and has become a more reliable platform for not only clients but also servers. Mocha.js (or Mocha for short) is a feature-rich JavaScript testing framework based on Node.js. It provides a platform and API for building standalone server-side applications, based on Google's V8 JavaScript engine.

Note: To start learning this JavaScript tutorial, you need to be familiar with the basics of NodeJS and JavaScript programming languages.

Tutorial Overview:

  1. Mocha Test Build
  • Introduction
  • Installation
  • Installing the Chai Assertion module
  • Test suite and test case structure
  • Build tests with Mocha
  • Test suites and test cases running Mocha
  • Manage synchronization of asynchronous test code
  1. Using the Javascript Selenium 3 API integrated with MochaJS
  • Introduction to Selenium
  • Selenium installation
  • WebDriver construct
  • Integrate MochaJS with Selenium WebDriver 3

Version used:

  • Node version: 6.10.1 (LTS)
  • Mocha: 2.5.3
  • WebDriverJS: 3.3.0
  1. Build tests with Mocha

Mocha Introduction

As mentioned earlier, Mocha is a JavaScript testing framework that runs tests on Node. Mocha is provided in the form of a Node package (via npm), allowing you to replace Node's standard "assert" functions with any assertion library, such as ChaiJS. Furthermore, Mocha has several components similar to Jasmine, another popular test automation framework we mentioned in the trend study of front-end and unit test automation).

Mocha provides an API that specifies a way to build test code into test suites and test case modules for execution and then generate test reports. Mocha provides two modes of operation: Command Line (CLI) or Programming (Mocha API).

Installation Mocha

If you want to use Mocha in the CLI, you should install it globally as Node.js.

<code>npm install -g mocha</code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Installing the Chai Assertion module

<code>npm install --save chai</code>
Copy after login
Copy after login
Copy after login
Copy after login
The

–save option is used to install modules within the scope of the project, rather than globally.

Test suite and test case structure

In Mocha, the test suite is defined by the "describe" keyword, which accepts a callback function. Test suites can contain sub/internal test suites, which can contain their own subtest suites, and so on. The test case is represented by the "it" function, which accepts a callback function and contains the test code.

Mocha supports test suite settings and test case settings functions. "before" means test suite settings, while "beforeEach" means test case settings. "beforeEach" is actually a common setup for every use case in the suite and will be executed before each use case.

As with the setup, Mocha supports test suites and test case teardown functions. "after" means test suite disassembly, and "afterEach" means test case disassembly, these two functions are executed after the test suite and each test case, respectively.

Create a file that "hosts" the test suite, such as test_suite.js, and write the following into it;

describe("Inner Suite 1", function(){

    before(function(){

        // 在测试套件执行之前执行某些操作
        // 无论是否有失败的用例

    });

    after(function(){

        // 测试套件执行完成后执行某些操作
        // 无论是否有失败的用例

    });

    beforeEach(function(){

        // 在测试用例执行之前执行某些操作
        // 无论是否有失败的用例

    });

    afterEach(function(){

        // 测试用例执行完成后执行某些操作
        // 无论是否有失败的用例

    });

    it("Test-1", function(){

        // 测试代码
        // 断言

    });

    it("Test-2", function(){

        // 测试代码
        // 断言

    });

    it("Test-3", function(){

        // 测试代码
        // 断言

    });

});
Copy after login
Copy after login
Copy after login
Copy after login

Run Mocha test suite and test cases

Mocha supports three test execution methods: the entire test suite file, the test filtered in the "grep" mode, and the test search (recursive option) in the directory tree grep filtering

Run the entire test suite file:

mocha /path/to/test_suite.js
Copy after login
Copy after login
Copy after login

Run a specific suite or test from a specific test suite file.

If a kit is selected, all sub-kits and/or tests will be performed.

mocha -g “Test-2” /path/to/test_suite.js
Copy after login
Copy after login
Copy after login

Run a specific suite or test file by recursively searching in the directory tree.

mocha --recursive -g “Test-2” /directory/
Copy after login
Copy after login

CLI options for extensions:

mocha --help
Copy after login
Copy after login

Manage synchronization of asynchronous test code

If you use asynchronous functions with Mocha and are not handled correctly, you may find yourself having trouble coping. If you want to use asynchronous code in your test cases (such as http requests, files, selenium, etc.), follow the following guidelines to overcome unexpected results:

  1. done function

In the test function (it) you need to pass the done function into the callback chain - this ensures that it is executed after your last step.

The following example emphasizes the done function. In this case, a three-second timeout will occur at the end of the test function.

<code>npm install -g mocha</code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
  1. Return to Promise

Returning Promise is another way to ensure that Mocha has executed all lines of code when using an asynchronous function (in this case the "done" function is not required.)

<code>npm install --save chai</code>
Copy after login
Copy after login
Copy after login
Copy after login
  1. Javascript Selenium 3 Integration with MochaJS

Introduction to Selenium

Selenium is a library that controls web browsers and simulates user behavior. More specifically, Selenium provides users with a specific language library API called "binding". "Binding" acts as a client to perform requests on intermediate components and acts as a server to ultimately control the browser.

Selenium API or binding now exists in all popular development languages. All language implementations now agree to maintain consistency in API function naming conventions.

The intermediate components may be the actual webdriver, selenium-standalone-server found locally in each Selenium package, as well as the vendor's native browser control drivers—such as Mozilla's Geckodriver, Chrome's chromedriver, etc. Additionally, Selenium webdriver communicates with browser drivers through "JsonWired Protocol" and becomes the W3C web standard.

Selenium installation

We will quickly learn about Selenium and NodeJS implementation before delving into the integration of Selenium and MochaJS.

In order to use JavaScript's Selenium API (or Selenium JavaScript binding), we should install the corresponding module:

describe("Inner Suite 1", function(){

    before(function(){

        // 在测试套件执行之前执行某些操作
        // 无论是否有失败的用例

    });

    after(function(){

        // 测试套件执行完成后执行某些操作
        // 无论是否有失败的用例

    });

    beforeEach(function(){

        // 在测试用例执行之前执行某些操作
        // 无论是否有失败的用例

    });

    afterEach(function(){

        // 测试用例执行完成后执行某些操作
        // 无论是否有失败的用例

    });

    it("Test-1", function(){

        // 测试代码
        // 断言

    });

    it("Test-2", function(){

        // 测试代码
        // 断言

    });

    it("Test-3", function(){

        // 测试代码
        // 断言

    });

});
Copy after login
Copy after login
Copy after login
Copy after login

At this point, it should be clear that Javascript Selenium WebDriver can also be called Webdriverjs (although not in npm). Webdrivejs is different from other libraries/modules (such as WebdriverIO, Protractor, etc.). selenium-webdriver is the official open source basic JavaScript Selenium library, while other libraries are wrapper libraries/frameworks built on top of the webdriverjs API, claiming to enhance availability and maintenance.

In NodeJS code, modules are used in the following ways:

mocha /path/to/test_suite.js
Copy after login
Copy after login
Copy after login

WebDriver construct

To be able to use Selenium, we should build the corresponding "webdriver" object, which will then control our browser. Below, we can see how we use the "Builder" pattern to build webdriver objects by linking multiple functions.

Builder with options

mocha -g “Test-2” /path/to/test_suite.js
Copy after login
Copy after login
Copy after login

In the above code, we have successfully built a WebDriver object that aggregates configurations of multiple browsers (note the "options" method), although the forBrowser() method explicitly sets firefox.

The user can set the SELENIUM_BROWSER environment variable at runtime to set the desired browser. It will override any options set by forBrowser because we have set multiple browser features via setOptions.

Browser properties can contain multiple types of information, depending on the browser being tested. For example, in the properties of Mozilla, we can set the required "profile" configuration as follows:

<code>npm install -g mocha</code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Then, in the Builder snippet above, we can add:

<code>npm install --save chai</code>
Copy after login
Copy after login
Copy after login
Copy after login

Builder with features

The Selenium WebDriver JavaScript API documentation describes several ways to build a webdriver. Another possible approach is to set all required driver configurations to function:

describe("Inner Suite 1", function(){

    before(function(){

        // 在测试套件执行之前执行某些操作
        // 无论是否有失败的用例

    });

    after(function(){

        // 测试套件执行完成后执行某些操作
        // 无论是否有失败的用例

    });

    beforeEach(function(){

        // 在测试用例执行之前执行某些操作
        // 无论是否有失败的用例

    });

    afterEach(function(){

        // 测试用例执行完成后执行某些操作
        // 无论是否有失败的用例

    });

    it("Test-1", function(){

        // 测试代码
        // 断言

    });

    it("Test-2", function(){

        // 测试代码
        // 断言

    });

    it("Test-3", function(){

        // 测试代码
        // 断言

    });

});
Copy after login
Copy after login
Copy after login
Copy after login

Note that if setOptions are set after withCapabilities, the configuration will be overwritten (for example, proxy configuration).

Selenium WebDriver Control Flow and Promise Management

Selenium WebDriver behaves similarly because JavaScript and NodeJS are based on the asynchronous principle. To avoid callback pyramids and help test engineers improve scripting experience and code readability and maintainability, the Selenium WebDriver object contains a Promise manager using "ControlFlow". "ControlFlow" is a class responsible for asynchronous webdriver command execution.

In fact, each command is executed on the driver object and returns a promise. Unless you need to process the parsed Promise value, you do not need to nest the next command in "then" as shown below:

mocha /path/to/test_suite.js
Copy after login
Copy after login
Copy after login

Tips for JavaScript testing Selenium WebDriver and Mocha

  1. driver is a webdriver object, not a Promise object
  2. driver.getTitle() or driver.get(url) or any other Selenium command returns a Promise object!

This means we can do the following:

mocha -g “Test-2” /path/to/test_suite.js
Copy after login
Copy after login
Copy after login
  1. In addition, since the driver itself is asynchronous, the following operations will not work:
mocha --recursive -g “Test-2” /directory/
Copy after login
Copy after login

Note: title is a Promise object, not the actual parsed value.

MochaJS Selenium WebDriver

Generally speaking, Selenium WebDriver can be integrated with MochaJS because it is used for any normal NodeJS script. However, since Mocha doesn't know when the asynchronous function is completed before calling done() or returning a Promise, we have to handle it very carefully.

Promise-based

The Selenium command is automatically registered to ensure that the webdriver command is executed in the correct order and should return a promise.

The following code shows the (before, beforeEach, afterEach) or test case body it hook.

mocha --help
Copy after login
Copy after login

The following will be performed:

  1. Loading the browser page of "my_service"
  2. Locate text field with id "username"
  3. Fill in text fields with id "username" with "my_username"
  4. Search the page title and check if it is equal to "my_title"
  5. WebDriver Exit and the browser window closes. The browser process terminates.

Selenium Webdriver Support for MochaJS

To perform JavaScript tests using Selenium WebDriver and Mocha in an easy way, WebDriver promotes the use of MochaJS by wrapping MochaJS test functions (before, beforeEach, it, etc.) using test objects. This creates a scope that provides awareness about the use of WebDriver. Therefore, there is no need to return a Promise.

First, the corresponding module should be loaded:

<code>npm install -g mocha</code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

All Mocha functions start with "test." as follows:

<code>npm install --save chai</code>
Copy after login
Copy after login
Copy after login
Copy after login

and so on. Then, the above code is completely rewritten as:

describe("Inner Suite 1", function(){

    before(function(){

        // 在测试套件执行之前执行某些操作
        // 无论是否有失败的用例

    });

    after(function(){

        // 测试套件执行完成后执行某些操作
        // 无论是否有失败的用例

    });

    beforeEach(function(){

        // 在测试用例执行之前执行某些操作
        // 无论是否有失败的用例

    });

    afterEach(function(){

        // 测试用例执行完成后执行某些操作
        // 无论是否有失败的用例

    });

    it("Test-1", function(){

        // 测试代码
        // 断言

    });

    it("Test-2", function(){

        // 测试代码
        // 断言

    });

    it("Test-3", function(){

        // 测试代码
        // 断言

    });

});
Copy after login
Copy after login
Copy after login
Copy after login

Conclusion

In this tutorial, we have the opportunity to experience JavaScript testing using Selenium WebDriver and MochaJS. We should remember that there are major differences due to the asynchronous nature of NodeJS, MochaJS, and Selenium WebDriver compared to other programming language bindings.

As long as we continue to return the Promise in any function that creates the Promise (custom test library functions or MochaJS hooks/test cases), Mocha will execute them in the correct order.

Other frameworks such as WebdriverIO, Protractor, and CodeseptJS provide wrapper solutions that can hide some configurations for users and provide some enhanced Promise processing for a better scripting experience, which many test automation experts may Found this useful.

FAQs (FAQs) about testing JavaScript with Selenium WebDriver and Mocha

How to set up Selenium WebDriver for JavaScript tests?

Setting up Selenium WebDriver for JavaScript tests includes several steps. First, you need to install Node.js and npm (Node package manager) on your system. After the installation is complete, you can use npm to install Selenium WebDriver by running the command npm install selenium-webdriver. You also need to install a browser driver, such as ChromeDriver for Google Chrome, which can be done by running npm install chromedriver. Once these installations are complete, you can start writing test scripts in JavaScript using Selenium WebDriver.

What is Mocha and why use it with Selenium WebDriver?

Mocha is a popular JavaScript testing framework that provides a simple and flexible way to write and organize test cases. It is often used with Selenium WebDriver because it provides features like asynchronous testing, which is critical to handling delayed operations such as network requests and browser operations. Mocha also provides concise and clear syntax to make your test cases easier to write and understand.

How to write basic test cases using Selenium WebDriver and Mocha?

Writing basic test cases using Selenium WebDriver and Mocha includes creating a new JavaScript file and writing test cases in Mocha describe and it blocks. In this block, you can use Selenium WebDriver's API to interact with the browser, such as navigating to a web page, interacting with elements, and checking their properties. Here is a basic example:

<code>npm install -g mocha</code>
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

How to handle asynchronous operations in my test cases?

You can use JavaScript's async/await syntax to handle asynchronous operations in test cases. This allows you to write asynchronous code in a synchronous manner, making it easier to read and understand. In the context of Selenium WebDriver, operations such as navigating to a web page, interacting with elements, and waiting conditions are asynchronous and can be processed using async/await.

How to run my test cases using Mocha?

To run test cases with Mocha, you can use the mocha command followed by the path to the test file. For example, if your test file is named test.js, you can run it using the command mocha test.js. Mocha will automatically find and run all test cases in this file.

How to use assertions in my test case?

Assertions in test cases can be used to verify that certain conditions are met. For example, you might want to assert that the title of the web page meets your expectations after performing a search. Assertions can be written using JavaScript's built-in assert module or third-party libraries such as Chai.

How to handle errors in my test cases?

The JavaScript try/catch syntax can be used to handle errors in test cases. This allows you to capture any errors that occur during test case execution and handle them appropriately, for example by logging errors and failing the test case.

How to interact with elements on a web page?

You can use Selenium WebDriver's API to interact with elements on a web page. This includes clicking on an element, typing in the input field, and reading element properties. These operations are performed using the driver.findElement method, which returns a WebElement object that you can interact with.

How to wait for conditions in my test case?

You can wait for conditions in my test case using Selenium WebDriver's driver.wait method. This method takes a conditional and optional timeout and waits until the condition is met or the timeout is reached. You can use the until module to create a condition, such as until.titleIs to wait for the title of the web page to be a value.

How to run my test cases in different browsers?

You can run test cases in different browsers by specifying the browser when creating a WebDriver instance. For example, you can run test cases in Firefox using new Builder().forBrowser('firefox') or run them in Chrome using new Builder().forBrowser('chrome'). You need to install the appropriate browser driver to make it work.

The above is the detailed content of How to Test Your JavaScript with Selenium WebDriver and Mocha. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template