To automate browser tests with Selenium and JavaScript, install Selenium’s Node.js binding, create a WebDriver session, navigate to your app, interact with elements, assert the visible result, and always close the session. The example below uses Node.js, Selenium WebDriver, and Mocha; Selenium controls the browser, while Mocha organizes and runs the test.
What you need before writing a test
- Node.js: Selenium’s current JavaScript API reference specifies Node.js 22 or later. Check the JavaScript API reference for the current requirement before installing.
- A browser: Choose the browser you want to test, such as Chrome, Firefox, or Edge.
- A test runner: The example uses Mocha, a common JavaScript choice in Selenium’s documentation. Jest is another option; a runner is not required to control the browser, but it helps organize tests and lifecycle hooks.
Selenium WebDriver is an interface for automating browsers. The JavaScript binding runs in Node.js and communicates with a browser-specific driver, which then controls the browser. Selenium’s official documentation describes WebDriver as a W3C Recommendation. See Selenium WebDriver documentation for the protocol and browser automation concepts.
Install Selenium and Mocha
Create a project directory, initialize an npm project, and install the browser automation package and test runner:
mkdir selenium-js-tests
cd selenium-js-tests
npm init -y
npm install selenium-webdriver
npm install --save-dev mocha
The Selenium package installation command is npm install selenium-webdriver. Selenium Manager can handle browser-driver setup when you have not provided a driver yourself. Automated browser management is documented as available starting with Selenium 4.11.0; that does not guarantee every environment can download a browser or driver. Network access, permissions, cache state, and CI restrictions can affect setup.
Recommended Free Tools
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
Write a browser test with a reliable lifecycle
Save the following as test/search.test.js. It opens a browser, searches a page, waits for the expected result, checks it with Node’s assertion library, and quits the browser even if an assertion fails.
const { Builder, By, until } = require('selenium-webdriver');
const assert = require('node:assert/strict');
describe('website search', function () {
this.timeout(30000);
let driver;
before(async function () {
driver = await new Builder().forBrowser('chrome').build();
});
after(async function () {
if (driver) {
await driver.quit();
}
});
it('shows results for a search term', async function () {
await driver.get('https://www.selenium.dev/');
const searchButton = await driver.findElement(By.css('button[aria-label="Search"]'));
await searchButton.click();
const searchInput = await driver.wait(
until.elementLocated(By.css('input[placeholder="Search"]')),
10000,
'Search input did not appear'
);
await searchInput.sendKeys('WebDriver');
const result = await driver.wait(
until.elementLocated(By.css('a[href*="webdriver"]')),
10000,
'A WebDriver search result did not appear'
);
assert.ok(await result.isDisplayed(), 'Expected a visible WebDriver result');
});
});
Page structure changes over time, so treat the selectors in this illustrative test as selectors to verify against the live page before relying on it. For your own application, prefer stable, intentional selectors—such as a test-specific attribute or accessible name—over brittle selectors tied to layout or generated class names.
Run it
Add a script to package.json:
{
"scripts": {
"test": "mocha"
}
}
Then run the test from the project directory:
npm test
Mocha discovers files in its default test directory. The test’s before hook starts one browser session, and after closes it. Selenium’s documentation also shows Node’s assert for checking page titles and confirmation messages. The lifecycle pattern is more important than this particular runner: if setup succeeds and a test fails, teardown should still release the browser session.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
Synchronize on page conditions, not guessed delays
Modern pages often render or update asynchronously. A fixed sleep only proves that a period elapsed; it does not prove that the element or state your test needs is ready. Use an explicit wait for the condition required by the next action or assertion, as the sample does for locating the input and result.
Selenium documents multiple waiting strategies, and the precise choice depends on the condition and application behavior. Consult the current waiting strategies documentation rather than applying a global delay or mixing wait styles without understanding their interaction. Wait for meaningful states—an element to exist, become visible, or become enabled—before acting on it.
Choose selectors and assertions that test user outcomes
A useful browser test follows the user-visible path without coupling itself unnecessarily to implementation details:
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
- Navigate with
driver.get(url). - Locate a control using
By.css(), an accessible name, or another locator suited to the application. - Act with browser interactions such as
click()orsendKeys(). - Wait for the resulting page state.
- Assert a relevant outcome, such as a confirmation message, changed title, or visible result.
Keep assertions tied to what the feature promises. A test that only checks that a click did not throw an error can pass even when the intended outcome never occurred. Where possible, use selectors your application deliberately maintains for tests, and assert the resulting state rather than a transient implementation detail.
Run locally, then move to remote browsers when needed
Start with a local browser while developing a test. It is simpler to inspect the browser and diagnose a selector or timing problem. When you need browser coverage across machines or operating systems, or more execution capacity, Selenium can connect to a remote WebDriver through Selenium Server; Selenium Grid is the project’s option for distributing tests across machines and platform combinations.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Fix the driver behind crashes, sound loss and screen glitches3Clear out junk files and repair common Windows errorsThe JavaScript API documents remote configuration with Builder().usingServer(...) or the SELENIUM_REMOTE_URL environment variable. Remote execution adds infrastructure and configuration to the test, so adopt it when the coverage or capacity need justifies that cost. See the Selenium Grid overview and the JavaScript API reference for current setup details.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
When WebDriver BiDi is useful
Classic WebDriver commands are a natural fit for navigating, locating elements, and performing actions. If a test also needs event-driven browser signals—such as network requests, console messages, or JavaScript errors—WebDriver BiDi may be relevant. Selenium describes BiDi as a bidirectional W3C protocol that adds a WebSocket connection for receiving browser events.
Do not assume every browser and JavaScript binding implements every BiDi feature equally. Confirm support for the specific event and browser combination you need before making it part of a test design. Read Selenium’s WebDriver BiDi documentation for the current capabilities and guidance.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Common Selenium JavaScript test problems
| Symptom | Likely cause | What to do |
|---|---|---|
| Browser or driver cannot start | The browser is unavailable, driver setup is blocked, or the environment cannot download required files. | Verify the browser is installed and supported in the environment. Check network access, permissions, and Selenium Manager’s ability to use its cache or download what it needs. In restricted CI environments, provide browser and driver setup explicitly. |
| Element not found | The selector does not match the current page, or the page has not reached the state where the element exists. | Inspect the rendered page and selector, then wait for the relevant condition before locating or interacting with the element. |
| Element is found but interaction fails | The element may be hidden, disabled, covered, or not yet ready for interaction. | Wait for the appropriate visible or enabled state and check that the target is the intended control. Avoid treating a successful lookup as proof the element is actionable. |
| Test passes locally but fails remotely or in CI | Browser versions, operating systems, network conditions, permissions, or timing may differ. | Record which browser and environment are used, use condition-based waits, and reproduce the test in the same remote configuration where possible. |
| Browser processes remain after a failed test | The session was not closed after an error or assertion failure. | Put driver.quit() in a reliable teardown path such as Mocha’s after hook or a finally block. |
Or skip the browser setup
If your goal is to capture a page image or PDF rather than interact with and assert on a live browser workflow, ScreenshotNeo offers a one-request screenshot API and an MCP server. Selenium is the right fit for browser tests that need actions and assertions; ScreenshotNeo is a separate option for capturing page output.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
For example, this cURL request saves a WebP screenshot of Stripe:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo documentation for API options. Before capture, it accepts cookie/consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each of those steps can be turned off. Bot checks/CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and responses indicate the page verdict and billing status in headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000.
Sign up for ScreenshotNeo’s free plan to try 1,000 screenshots a month without a card.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →

