Careeroza
Console Logs and JavaScript Errors
Listening With LogInspector (BiDi)
A page can look fine while JavaScript errors are thrown in the background. Capture them and fail the test, or attach them to the report.
import org.openqa.selenium.bidi.module.LogInspector;
import org.openqa.selenium.bidi.log.*;
ChromeOptions options = new ChromeOptions();
options.setCapability("webSocketUrl", true);
WebDriver driver = new ChromeDriver(options);
List<String> jsErrors = new CopyOnWriteArrayList<>();
try (LogInspector logs = new LogInspector(driver)) {
logs.onConsoleEntry(entry -> System.out.println("console." + entry.getMethod() + ": " + entry.getText()));
logs.onJavaScriptException(ex -> jsErrors.add(ex.getText()));
driver.get("https://shopease.example.com/cart");
driver.findElement(By.id("checkout")).click();
}
Assert.assertTrue(jsErrors.isEmpty(), "JavaScript errors: " + jsErrors);What You See
Example
mvn test -Dtest=CartConsoleTestExample output
console.log: cart loaded, 2 items console.warn: coupon service slow (1840 ms) [ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0 [ERROR] CartConsoleTest.noJsErrorsOnCheckout:38 JavaScript errors: [TypeError: Cannot read properties of undefined (reading 'pincode')] expected [true] but found [false]
Note: This caught a real bug: the checkout script crashed for users without a saved address, even though the button still looked normal.