Core points
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:
Version used:
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).
If you want to use Mocha in the CLI, you should install it globally as Node.js.
<code>npm install -g mocha</code>
Installing the Chai Assertion module
<code>npm install --save chai</code>
–save option is used to install modules within the scope of the project, rather than globally.
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(){ // 测试代码 // 断言 }); });
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
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
Run a specific suite or test file by recursively searching in the directory tree.
mocha --recursive -g “Test-2” /directory/
CLI options for extensions:
mocha --help
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:
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>
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>
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.
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(){ // 测试代码 // 断言 }); });
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
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.
mocha -g “Test-2” /path/to/test_suite.js
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 set
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>
Then, in the Builder snippet above, we can add:
<code>npm install --save chai</code>
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(){ // 测试代码 // 断言 }); });
Note that if setOptions are set after withCapabilities, the configuration will be overwritten (for example, proxy configuration).
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
Tips for JavaScript testing Selenium WebDriver and Mocha
This means we can do the following:
mocha -g “Test-2” /path/to/test_suite.js
mocha --recursive -g “Test-2” /directory/
Note: title is a Promise object, not the actual parsed value.
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.
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
The following will be performed:
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>
All Mocha functions start with "test." as follows:
<code>npm install --save chai</code>
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(){ // 测试代码 // 断言 }); });
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
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.
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.
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>
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.
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.
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.
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.
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.
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.
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!