This guide walks you through setting up and writing automated browser tests using Selenium WebDriver with JavaScript. You’ll learn how to install the necessary packages, write a basic test script, run it against a real browser, and handle common pitfalls. By the end, you’ll have a working test that can be extended to cover your own web applications.
What You’ll Need
- Node.js (version 14 or later) installed on your machine.
- A code editor (like VS Code, Atom, or any text editor).
- Basic knowledge of JavaScript and command-line usage.
- A modern web browser (Chrome, Firefox, or Edge) installed.
- Internet access to download npm packages and browser drivers.
Step-by-Step
- Create a new project directory. Open your terminal and run:
mkdir selenium-test && cd selenium-test. This will be the home for your test files. - Initialize a Node.js project. Run
npm init -yto create apackage.jsonfile with default settings. This file tracks your project’s dependencies. - Install Selenium WebDriver. Run
npm install selenium-webdriver. This package provides the JavaScript bindings for Selenium. - Install the browser driver. Selenium needs a driver to communicate with your chosen browser. For Chrome, install chromedriver:
npm install chromedriver. For Firefox, usenpm install geckodriver. For Edge, usenpm install msedgedriver. These packages automatically download the correct driver binary for your system. - Create a test script. Create a file named
test.jsin your project directory. This will contain your test code. - Write a basic test. Open
test.jsand add the following code:const { Builder, By, until } = require('selenium-webdriver'); (async function example() { let driver = await new Builder().forBrowser('chrome').build(); try { await driver.get('https://www.example.com'); await driver.findElement(By.tagName('h1')).getText().then(text => { console.log('H1 text:', text); }); } finally { await driver.quit(); } })();This script launches Chrome, navigates to example.com, fetches the text of the first
h1element, and prints it to the console. Thefinallyblock ensures the browser closes even if an error occurs. - Run the test. In your terminal, execute
node test.js. You should see the browser open, load the page, and then close. The console will display the H1 text (which is “Example Domain” on example.com). - Add assertions (optional but recommended). Install a test framework like Mocha or Jest to make your tests more robust. For example, install Mocha:
npm install mocha. Then modify your script to usedescribeanditblocks, and use assertions to verify expected behavior. This allows you to run multiple tests and get clear pass/fail reports. - Use WebDriver’s built-in waits. To handle dynamic content, replace
findElementwithwaitanduntil. For example:await driver.wait(until.elementLocated(By.id('submit')), 10000);. This waits up to 10 seconds for an element to appear before proceeding. - Run tests in headless mode (for CI). To run without a visible browser, add the argument
--headlessto the browser options. For Chrome, you’d do:new Builder().forBrowser('chrome').setChromeOptions(new chrome.Options().addArguments('--headless')). This is useful for continuous integration environments.
Common Mistakes
- Forgetting to install the driver. Without chromedriver or geckodriver, Selenium throws a “SessionNotCreatedError” or similar. Always install the matching driver for your browser.
- Hard-coding sleeps. Using
driver.sleep(5000)to wait for elements is fragile and slows down tests. Use explicit waits withuntilinstead. - Not closing the driver. Leaving the browser open after a test can cause resource leaks and interfere with subsequent runs. Always use
driver.quit()in afinallyblock or after each test. - Targeting elements incorrectly. Using overly specific selectors (like absolute XPath) makes tests brittle. Prefer IDs, CSS classes, or data attributes that are stable across page updates.
- Ignoring asynchronous behavior. Forgetting to
awaitpromises can lead to race conditions where the test proceeds before the page is ready. Always await WebDriver calls.
Tips
- Use a test framework like Mocha or Jest to organize tests and get readable output. This also makes it easier to run tests in CI pipelines.
- Keep selectors in a separate file (e.g., a page object model) to improve maintainability. If the UI changes, you only update one place.
- Run tests in headless mode for speed and to avoid interrupting your work. You can toggle this with an environment variable.
- Use
driver.manage().window().setRect({width, height})to test responsive layouts by resizing the browser window. - Take screenshots on failure to help debug issues. Use
driver.takeScreenshot()and save the base64 string to a file. - Parallelize tests by using Selenium Grid or a cloud service, but start with local sequential runs to ensure stability.
Troubleshooting
- Browser doesn’t launch. Check that the driver is installed and matches your browser version. Run
chromedriver --versionto verify. Also ensure your browser is up to date. - “SessionNotCreatedError” This usually means the driver and browser versions are incompatible. Update both to the latest stable versions, or use a driver that matches your browser exactly.
- Element not found. The element may not be loaded yet. Use explicit waits to give the page time to render. Also double-check the selector—try using the browser’s dev tools to inspect the element.
- Timeout errors. If a wait times out, the element never appeared. Check if the element is in an iframe or shadow DOM; you may need to switch context first.
- Permission errors on Linux. Some drivers require the browser to be run with a virtual display (e.g., Xvfb). Install and start Xvfb, or use headless mode.
- Tests run but no browser window appears. You’re likely in headless mode. Remove the
--headlessargument to see the browser.
Frequently Asked Questions
Can I use Selenium with other browsers like Safari?
Yes, Selenium supports Safari through the safaridriver that comes with macOS. However, you need to enable the “Allow Remote Automation” option in Safari’s Develop menu. For Internet Explorer, you’d need IEDriverServer, but it’s deprecated on modern Windows.
How do I handle pop-ups or alerts?
Use driver.switchTo().alert() to interact with JavaScript alerts. For browser-level pop-ups like authentication dialogs, you can pass credentials in the URL (e.g., https://user:pass@example.com) or use the webdriver.Browser options.
Is it possible to run tests in parallel?
Yes, you can run multiple instances of the driver concurrently, but be cautious about resource usage. For large suites, consider using Selenium Grid or a cloud provider like Sauce Labs or BrowserStack.
How do I wait for a page to load completely?
By default, WebDriver waits for the document.readyState to be ‘complete’. However, for SPAs that load content dynamically, use explicit waits for specific elements or conditions, not just page load.
Can I use Selenium with JavaScript and TypeScript?
Yes, you can write tests in TypeScript and compile them to JavaScript. The selenium-webdriver package includes type definitions, so you get autocompletion and type checking.
What’s the difference between findElement and findElements?
findElement returns the first matching element and throws an error if none found. findElements returns an array of all matches (empty if none). Use the latter when you expect multiple elements, like a list of items.
Related
General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.
More in this bed
- How to Factory Reset iPad If You Forgot Password
- Ubuntu in Windows Store: Which Editions Work?
- Secure Guest Account on Windows 11: Step-by-Step
- Stop Outlook From Changing Hyperlink Font
- Hiberfil.sys: What It Is & How to Delete It
- How to Make a Mask on Snapchat: Step-by-Step