Mocha does not read playwright.config.ts as Playwright Test does. A Mocha test that imports the standalone playwright package must load environment variables itself and pass launch or context options explicitly. If your tests depend on Playwright Test features such as use.baseURL, projects, fixtures, retries, storage state, or webServer, run them with npx playwright test instead.
Why Mocha appears to ignore playwright.config.ts
There are two different execution models:
- Playwright Test: the
@playwright/testrunner discoversplaywright.config.*and applies its top-level runner settings and the browser/context settings underuse. - Mocha plus Playwright: Mocha runs the tests, while the
playwrightlibrary launches browsers. No Playwright Test runner is involved, souse,projects, fixtures, retries, andwebServerare not imported automatically.
The file can be perfectly valid and still have no effect. The fix is to choose one runner and configure it according to that runner’s model.
Choose the correct fix
| What your suite needs | Correct action |
|---|---|
Fixtures, use, projects, retries, storage state, or webServer |
Use Playwright Test and run npx playwright test. |
| Existing Mocha hooks, reporters, or Mocha plugins must remain | Keep Mocha, load configuration in the Mocha process, and pass values to Playwright API calls. |
| Mocha is selecting the wrong configuration file | Pin it with npx mocha --config .mocharc.cjs and inspect discovery. |
| The browser launches but opens the wrong URL | Check dotenv path, variable spelling, and the value immediately before navigation. |
| Launch fails before a test runs | Use the browser diagnostic namespace DEBUG=pw:browser. |
Fix A: run the suite with Playwright Test
Use this route when the configuration is intended to control the Playwright Test runner. A minimal TypeScript configuration is:
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
baseURL: process.env.BASE_URL,
},
});
Run it with:
npx playwright test
Runner controls such as testDir, projects, reporter, retries, workers, and webServer belong at the top level. Browser and context controls, including baseURL and storageState, belong under use. Those values are inherited by contexts created by Playwright Test and can be overridden by a project or an individual test.
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.
Do not invoke the same files with mocha and expect this configuration to be applied. If the tests use Mocha’s describe, it, and hooks, converting the suite to Playwright Test may be a larger change; in that case use Fix B.
Fix B: keep Mocha and configure Playwright as a library
In Mocha, load environment variables before importing code that reads process.env, then construct browser and context options explicitly. The following CommonJS setup is runnable as-is:
// test/setup.js
require('dotenv').config({
path: require('node:path').resolve(__dirname, '../../.env'),
});
const { chromium } = require('playwright');
exports.createBrowser = () => chromium.launch({
headless: process.env.HEADLESS !== 'false',
});
exports.baseURL = process.env.BASE_URL;
// test/example.spec.js
const assert = require('node:assert/strict');
const { createBrowser, baseURL } = require('./setup');
let browser;
before(async () => {
browser = await createBrowser();
});
after(async () => {
await browser.close();
});
test('opens the configured URL', async () => {
const page = await browser.newPage();
await page.goto(baseURL);
assert.equal(await page.title(), 'Expected title');
});
Mocha’s global test function is commonly named it; if your project uses a custom interface that exposes test, keep that interface. Otherwise change the example’s test(...) call to it(...).
Pass context settings where they belong
In standalone Playwright, launch options go to chromium.launch(); page behavior such as the base URL, storage state, locale, or viewport goes to browser.newContext():
Free tools Windows power users keep installed
One-click scans. No signup required.
const context = await browser.newContext({
baseURL: process.env.BASE_URL,
storageState: process.env.STORAGE_STATE,
viewport: { width: 1440, height: 900 },
});
const page = await context.newPage();
There is no automatic inheritance from a use block because Mocha did not create the context.
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.
Load dotenv before reading process.env
A frequent cause of an undefined BASE_URL is reading the variable before dotenv has loaded it. Put require('dotenv').config(...) or import 'dotenv/config' at the start of the process, before importing modules that capture configuration at module scope.
Anchor the path when .env is outside the current working directory. A command launched from a subdirectory can otherwise resolve a relative path to a different file or to nothing:
require('dotenv').config({
path: require('node:path').resolve(__dirname, '../../.env'),
});
For an ES module setup, the equivalent ordering is:
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallCrashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteimport 'dotenv/config';
import { chromium } from 'playwright';
If the file has a nonstandard location, use an explicit path based on the module directory rather than assuming the shell’s working directory.
Verify names, timing, and option placement
Use the exact variable name
Environment keys are case-sensitive in common CI and Unix environments. BASE_URL, Base_URL, and baseUrl are different keys. Confirm the name in the .env file, shell command, CI definition, and JavaScript or TypeScript access all match.
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.
Inspect the handoff without leaking secrets
Immediately before launching or navigating, print a presence check or a redacted value:
const resolvedBaseURL = process.env.BASE_URL;
console.log({
hasBaseURL: Boolean(resolvedBaseURL),
baseURL: resolvedBaseURL ? new URL(resolvedBaseURL).origin : undefined,
});
Do not log access tokens, cookies, authorization headers, or complete secret-bearing URLs in CI output.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Scan for outdated or missing drivers - takes under a minute3Repair Windows errors before they cause bigger problemsDo not put runner settings in a library call
Options such as projects, workers, retries, and reporter are Playwright Test runner settings. They do not belong in chromium.launch(). Conversely, standalone launch options such as headless must be passed to the browser API when Mocha owns execution.
Make Mocha load the intended configuration
Mocha has its own configuration discovery. It can search parent directories, and a repository can contain more than one .mocharc file or format. Pin the file when selection is uncertain:
npx mocha --config .mocharc.cjs
Use --no-config when you need to prove that an automatically discovered file is affecting the run. Also inspect package.json scripts: npx playwright test and mocha are not interchangeable commands.
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
Shell and CI environment injection
Bash and compatible shells
BASE_URL=https://test.example npm test
PowerShell
$env:BASE_URL='https://test.example'
npm test
In CI, verify that the variable is exported into the test process rather than defined only in a separate shell step. A value visible in one job or step may not be present in the process that runs Mocha.
Diagnostics for stubborn failures
API activity
Set DEBUG=pw:api to expose Playwright API activity while Mocha runs:
DEBUG=pw:api mocha
Browser launch failures
Use the browser namespace when the failure occurs before a page exists:
DEBUG=pw:browser mocha
These logs help distinguish a missing environment value from an installation, executable, sandbox, or launch problem. Keep diagnostic output out of permanent logs if it contains sensitive request details.
Common symptoms and precise fixes
baseURLis undefined: Mocha is not applyinguse.baseURL. Load dotenv first, readprocess.env.BASE_URL, and pass it tonewContext({ baseURL }).- The .env file works locally but not in CI: the path is relative to a different working directory or the CI job does not export the variable. Resolve the path from
__dirnameand inspect the job environment. - Changing playwright.config.ts has no effect: the command is
mocha, notnpx playwright test. Either change the command or move the values into Mocha setup code. - A setting is rejected as an unknown browser option: it is probably a runner option placed in
chromium.launch(). Move it to Playwright Test’s top level or implement equivalent Mocha behavior explicitly. - The browser starts but navigation targets the wrong host: log the resolved origin immediately before
page.goto(); then check spelling, dotenv order, and which .env file was loaded. - The browser never starts: run with
DEBUG=pw:browser mochaand inspect the launch output before changing test assertions.
Or skip the browser setup
If your goal is simply to obtain a clean website screenshot rather than run a Mocha test, ScreenshotNeo provides a single HTTP request and an MCP server for AI clients. Its API accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and each response identifies the page verdict and billing status in headers.
Here is the one-call cURL form (see the ScreenshotNeo API documentation for all options):
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.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
The same request in Python:
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
And in Node.js:
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
ScreenshotNeo also supports an MCP server with take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 screenshots each month without a card; paid plans start at $5 for 3,000 shots. Sign up for the free plan.
FAQ
Can I make Mocha consume playwright.config.ts directly?
Not as a Playwright Test configuration. Mocha can have its own configuration, but values in Playwright Test’s use block must be transferred to standalone Playwright API calls.
Should I import @playwright/test in a Mocha test?
Only if you are intentionally moving to the Playwright Test runner. Mixing the two execution models does not make Mocha apply Playwright Test’s project and fixture lifecycle.
Does setting BASE_URL on the command line override .env?
dotenv loading and shell injection follow normal process-environment precedence in your application. Check the final value immediately before browser or context construction instead of assuming which source won.
Frequently Asked Questions
Can I make Mocha consume playwright.config.ts directly?
Not as a Playwright Test configuration. Mocha has its own configuration, while values in Playwright Test’s use block must be transferred to standalone Playwright API calls.
Should I import @playwright/test in a Mocha test?
Only when intentionally migrating to the Playwright Test runner; mixing the runners does not apply Playwright Test projects or fixtures to Mocha.
Does setting BASE_URL on the command line override .env?
Check the final value immediately before browser or context construction rather than assuming which source took precedence.
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.

