How to Fix PHPUnit and Selenium Tests That Stall with PhantomJS
Find whether PhantomJS, Selenium synchronization, or PHPUnit is hanging, then diagnose it with bounded waits, logs, isolation, and migration steps.

A PHPUnit test that appears frozen with PhantomJS can be waiting for a page condition, blocked in WebDriver, or stuck in PHPUnit while cleaning up a child process. Find the last command that completed, identify which process is still alive, and make the wait bounded so the failure becomes visible.
Quick diagnosis
- Record PHP, PHPUnit, Selenium server, PHP WebDriver binding, PhantomJS versions and executable paths.
- Run the test with an explicit wait and a finite timeout instead of an unbounded sleep or implicit wait.
- Enable PhantomJS WebDriver logs and preserve PHPUnit output.
- Run the same minimal scenario in another browser.
- Inspect the process tree and stderr if PHPUnit uses process isolation.
- Plan migration: PhantomJS is archived and Selenium deprecated its WebDriver support in Selenium 3.8.1.
Selenium’s official troubleshooting guide states: “The most common Selenium-related error is a result of poor synchronization.” Read the synchronization guidance.
1. Capture a reproducible baseline
Run these commands from the same shell, container, CI user and working directory that execute PHPUnit:

php --version
vendor/bin/phpunit --version
which phantomjs
phantomjs --version
java -version 2>&1 || true
Also record:
- Operating system, container image and CI runner.
- Selenium server and PHP binding versions.
- The PhantomJS path actually selected by
PATH. - Test timeout, implicit-wait and process-isolation settings.
- The final PHPUnit line printed and the last WebDriver command that completed.
- Whether PhantomJS, Selenium, PHP or a child test process remains alive.
The php-webdriver documentation lists Selenium 2.x, 3.x and 4.x compatibility considerations. Check the versions in your environment rather than assuming that a client, server, browser and driver combination is compatible.
2. Replace indefinite synchronization with an explicit wait
Do not start by increasing every timeout. First identify what the test needs: navigation, a title, an element, an asynchronous script or a network-backed state. Wait for that condition with a bounded timeout.
<?php
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\WebDriverExpectedCondition;
use Facebook\WebDriver\WebDriverBy;
$driver = RemoteWebDriver::create(
'http://127.0.0.1:4444/wd/hub',
DesiredCapabilities::phantomjs(),
10_000,
30_000
);
try {
$driver->get('https://example.test/dashboard');
$wait = new Facebook\WebDriver\WebDriverWait($driver, 10, 250);
$wait->until(
WebDriverExpectedCondition::presenceOfElementLocated(
WebDriverBy::cssSelector('[data-testid="dashboard-ready"]')
)
);
self::assertSame('Dashboard', $driver->getTitle());
} finally {
$driver->quit();
}
Use a condition that represents readiness. A fixed sleep(10) can be too short on a slow run and wastes time on a fast run. Keep the timeout finite so a missing element produces a useful exception.
Common readiness conditions
| What must be ready | Condition to wait for |
|---|---|
| Page navigation | Expected URL or title |
| Rendered component | Presence or visibility of a stable selector |
| Interactive control | Element is visible and enabled |
| AJAX result | Result selector, text, or application state marker |
| Async JavaScript | Use an async script callback with a script timeout |
Keep implicit waits small or disabled while debugging. Mixing a long implicit wait with explicit waits can make failures appear much slower because each element lookup may consume the implicit timeout.
3. Verify PhantomJS and enable WebDriver logs
Multiple PhantomJS installations are a frequent source of confusion. Check the executable as the PHPUnit process sees it, then run that exact path:

PHANTOM_BIN="$(command -v phantomjs)"
printf '%s\n' "$PHANTOM_BIN"
"$PHANTOM_BIN" --version
"$PHANTOM_BIN" --help | grep -E 'webdriver|remote-debugger'
PhantomJS’s command-line interface supports WebDriver mode and logging options. Start it with a log file and a useful level:
phantomjs \
--webdriver=8910 \
--webdriver-logfile=/tmp/phantomjs-webdriver.log \
--webdriver-loglevel=INFO
Use the same port in your PHP client. Preserve the log on CI even when the test fails. Look for session creation, the last command received, JavaScript errors and an early process exit. See the PhantomJS troubleshooting documentation and command-line reference.
Page-side diagnostics
For a page JavaScript exception or stalled resource, PhantomJS documents page.onError and callbacks such as onResourceRequested. Its remote debugger can be enabled with --remote-debugger-port:
phantomjs \
--webdriver=8910 \
--webdriver-logfile=/tmp/phantomjs-webdriver.log \
--remote-debugger-port=9000
These are legacy tools; use them to capture evidence, not as a reason to depend on PhantomJS indefinitely.
4. Isolate browser and driver behavior
Run the same small scenario against another browser. Selenium recommends trying commands in multiple browsers to help distinguish driver problems from test or application problems.
<?php
// Run this test once with PhantomJS and once with a current browser
// capability supported by your Selenium installation.
$driver = RemoteWebDriver::create(
'http://127.0.0.1:4444/wd/hub',
DesiredCapabilities::firefox(),
10_000,
30_000
);
try {
$driver->get('https://example.test/health');
self::assertStringContainsString('healthy', $driver->getPageSource());
} finally {
$driver->quit();
}
| Result | Most useful next focus |
|---|---|
| Only PhantomJS hangs | PhantomJS/GhostDriver behavior, unsupported commands, page JavaScript compatibility, TLS or network differences |
| Every browser hangs at the same action | Application readiness, server response, Selenium synchronization or test code |
| Driver exits but PHPUnit waits | Client timeout, process cleanup and the PHPUnit process tree |
5. Check whether PHPUnit is the process that is stuck
When the test stops, inspect the process tree from another shell:
ps -ef --forest | grep -E 'phpunit|php |phantomjs|selenium' | grep -v grep
lsof -nP -iTCP:8910 -sTCP:LISTEN
Ask which process remains:
- PhantomJS alive: inspect its WebDriver log and the last command.
- Selenium alive, browser gone: check driver compatibility and session teardown.
- PHP child alive: inspect process-isolation output and open pipes.
- Only PHPUnit alive: inspect cleanup, stream reads and test listeners.
PHPUnit issue #5993 reports an indefinite process-isolation hang in a specific environment (PHPUnit 10.5.36, PHP 8.3.12) when a child emits substantial stderr; the report points to a blocking stream read. It is a diagnostic lead, not proof that PhantomJS caused your stall. Reduce noisy child output, preserve stderr to a file, and test with process isolation changed temporarily to confirm whether the hang moves.
Always close the WebDriver session in a finally block. A historical Selenium issue, #349, shows that a client can wait before reporting a driver that exited immediately; a delayed timeout can therefore hide an early driver failure.
6. A minimal PHPUnit reproduction
<?php
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\WebDriverBy;
use Facebook\WebDriver\WebDriverWait;
use Facebook\WebDriver\WebDriverExpectedCondition;
use PHPUnit\Framework\TestCase;
final class PhantomSmokeTest extends TestCase
{
public function testHealthPage(): void
{
$driver = RemoteWebDriver::create(
'http://127.0.0.1:8910',
DesiredCapabilities::phantomjs(),
5000,
15000
);
try {
$driver->get('https://example.test/health');
(new WebDriverWait($driver, 5, 200))->until(
WebDriverExpectedCondition::presenceOfElementLocated(
WebDriverBy::cssSelector('body')
)
);
$this->assertStringContainsString('healthy', $driver->getPageSource());
} finally {
$driver->quit();
}
}
}
Replace the URL and readiness selector with values from your application. Run only this test, then add actions one at a time until the stall returns.
7. Decide whether to repair or migrate
The PhantomJS repository is archived and read-only. A Selenium issue records PhantomJS WebDriver deprecation in Selenium 3.8.1 and suggests headless Chrome or Firefox. Check the current browser and driver compatibility for your project before choosing an alternative; do not assume that changing one binary is sufficient.
| Decision axis | Question |
|---|---|
| Compatibility | Do your PHP binding, Selenium server, browser and driver versions support one another? |
| Reproduction | Does the failure occur only in PhantomJS? |
| Maintenance | Can the archived browser receive fixes needed by your application? |
| CI | Can your runner install and launch the replacement browser reliably? |
| JavaScript behavior | Does the replacement match the browser behavior your users need? |
8. Troubleshooting checklist
| Symptom | Likely cause | Fix |
|---|---|---|
| Nothing prints after navigation | Page load or synchronization wait | Wait for a specific selector or title with a bounded timeout; capture browser logs. |
| Element wait always times out | Wrong selector, frame, redirect or JavaScript error | Log URL and page source, switch into the correct frame, and inspect PhantomJS errors. |
| Works locally but hangs in CI | Different binary, PATH, network, TLS or display environment | Print versions and paths in CI and preserve WebDriver logs. |
| Only PhantomJS fails | Legacy browser or GhostDriver incompatibility | Reproduce in another browser and evaluate migration. |
| PHPUnit never exits | Child process, stderr pipe or missing teardown | Inspect the process tree, reduce child output and call quit() in finally. |
| Timeout appears much later than the failure | Client is waiting after a driver exited | Check driver logs and process lifetime before increasing timeouts. |
9. Performance, reliability and cost
- Use one small smoke test to diagnose, then run the full suite after the root cause is visible.
- Prefer condition-based waits to long sleeps; they reduce idle time and make failures actionable.
- Keep connection, page-load and script timeouts separate so a slow resource does not hide a dead driver.
- Capture logs only at the level needed for diagnosis, but retain them as CI artifacts when a failure occurs.
- Close sessions even on assertion failures to prevent orphaned browser processes from exhausting a runner.
- There is no reliable general PhantomJS speed or failure-rate figure in the available evidence; measure your own suite after each browser or driver change.
Or skip the browser setup
If your goal is to obtain a clean screenshot rather than maintain a PhantomJS test browser, ScreenshotNeo provides a single HTTP request. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups and chat widgets. Bot checks, blank pages, failed loads, timeouts and cache hits are not billed, and each response reports the result in X-Page-Verdict and X-Billed headers. Its MCP server provides take_screenshot, get_page_info and capture_pdf tools for Claude, Cursor and other MCP clients.
See the ScreenshotNeo API documentation for all options.
cURL
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
PHP
<?php
$url = 'https://api.screenshotneo.com/v1/shot';
$query = http_build_query([
'access_key' => 'YOUR_API_KEY',
'url' => 'https://stripe.com',
]);
$context = stream_context_create(['http' => ['timeout' => 90]]);
$data = file_get_contents($url . '?' . $query, false, $context);
if ($data === false) {
throw new RuntimeException('Screenshot request failed');
}
file_put_contents('shot.webp', $data);
Python
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
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}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
require('fs').writeFileSync('shot.webp', Buffer.from(await res.arrayBuffer()));
ScreenshotNeo includes full-page capture, element selectors, device presets, custom CSS and JavaScript, waits, request blocking, headers, cookies, geolocation, PDFs, caching, signed links, asynchronous jobs, bulk capture and a usage API. Free usage includes 1,000 screenshots each month with no card; paid plans start at $5 for 3,000 shots.
Create a free ScreenshotNeo account and get 1,000 screenshots a month with no card.
FAQ
Is PhantomJS still supported?
Its repository is archived and read-only, and Selenium deprecated its WebDriver support. Verify your project’s compatibility and plan a supported browser migration.
Should I increase the timeout first?
No. Identify the condition being awaited, add an explicit bounded wait, and inspect logs. Increase a timeout only when the condition is valid but legitimately slow.
How do I know whether PHPUnit or PhantomJS is stuck?
Inspect the process tree and the last log line. A live PhantomJS process points to browser or page behavior; a PHP child or PHPUnit process points to test cleanup or stream handling.
Can a screenshot API replace browser tests?
No. Use browser tests for interactions and assertions. A screenshot API is useful when you need rendered images or PDFs without maintaining a browser process.


