Ghost Inspector Assertions and Validations: Complete Guide
A browser test without assertions is just a script that clicks things. Assertions are what turn a recording into a meaningful test — they verify that the right outcomes happened, not just that the steps executed without crashing. Ghost Inspector provides several layers of assertion capability, from simple text checks to custom JavaScript expressions.
This guide covers every assertion type Ghost Inspector supports, when to use each one, and how to write assertions that catch real bugs without generating false positives.
How Assertions Work in Ghost Inspector
In Ghost Inspector, assertions are steps in your test that verify state rather than perform actions. When an assertion fails, the test fails at that step and subsequent steps are skipped. Each failing assertion captures a screenshot so you can see exactly what the browser looked like when the check failed.
You can add assertions during recording (by right-clicking elements) or by manually inserting assertion steps in the test editor after recording.
Text Assertions
Text assertions check the visible text content of an element. These are the most common assertion type and cover a wide range of verification scenarios.
Assert Element Contains Text
Check that an element contains a specific string:
| Field | Value |
|---|---|
| Step Type | Assert Element Contains Text |
| CSS Selector | #confirmation-message |
| Value | Your order has been placed |
This uses a substring match — the element just needs to contain the text, not equal it exactly. This is usually what you want, since surrounding whitespace or additional text won't cause failures.
Assert Element Text Equals
For exact matching when you need to verify the complete text content:
| Field | Value |
|---|---|
| Step Type | Assert Element Text Equals |
| CSS Selector | .cart-total |
| Value | $49.00 |
Use this for prices, counts, or any value where extra text would indicate a bug.
Assert Page Title
Check the browser tab title:
| Field | Value |
|---|---|
| Step Type | Assert Title |
| Value | Dashboard - MyApp |
Useful for verifying navigation completed correctly.
Assert URL
Verify the current page URL matches an expected value:
| Field | Value |
|---|---|
| Step Type | Assert URL |
| Value | https://yourapp.com/dashboard |
You can also use partial URL matching — the assertion passes if the URL contains the specified string. This handles dynamic URL parameters gracefully.
Element Presence and State Assertions
These assertions check whether elements exist or are visible, and what state they're in.
Assert Element Exists
Verify that an element is present in the DOM:
| Field | Value |
|---|---|
| Step Type | Assert Element Exists |
| CSS Selector | .success-banner |
Note: an element can exist in the DOM but be hidden with display: none. If you need to check visibility, use the next assertion type.
Assert Element Visible
Check that an element is both present and visible to the user:
| Field | Value |
|---|---|
| Step Type | Assert Element Visible |
| CSS Selector | #error-message |
This is the right assertion for UI elements that toggle visibility based on application state.
Assert Element Not Exists / Not Visible
The inverse assertions are equally important:
| Step Type | CSS Selector | Use Case |
|---|---|---|
| Assert Element Not Exists | .error-banner |
Verify no error after successful action |
| Assert Element Not Visible | #loading-spinner |
Verify loading state cleared |
Always pair success assertions with negative assertions where relevant. A test that only checks that the success message appears — but not that the error message is absent — misses a class of bugs.
Assert Element Count
Verify that exactly N elements matching a selector exist:
| Field | Value |
|---|---|
| Step Type | Assert Element Count |
| CSS Selector | .search-result |
| Value | 5 |
Useful for verifying list lengths, pagination results, and table rows.
Assert Checkbox Checked State
For form testing:
| Field | Value |
|---|---|
| Step Type | Assert Checkbox Is Checked |
| CSS Selector | #remember-me |
Ghost Inspector has separate assertion types for checked and unchecked state.
Form and Input Assertions
Assert Input Value
Verify the current value of a text input:
| Field | Value |
|---|---|
| Step Type | Assert Input Value |
| CSS Selector | #email-field |
| Value | user@example.com |
Useful for verifying that auto-populated fields, pre-filled forms, or edit flows load the correct existing values.
Assert Select Value
Check which option is selected in a dropdown:
| Field | Value |
|---|---|
| Step Type | Assert Select Value |
| CSS Selector | #country-select |
| Value | US |
The value matches the value attribute of the <option> element, not the visible label.
Screenshot Comparison Assertions
Ghost Inspector captures screenshots at every step. The screenshot comparison feature lets you assert that the visual appearance of a page hasn't changed.
How Screenshot Comparison Works
When you enable screenshot comparison for a test, Ghost Inspector:
- Runs the test and captures a screenshot
- Compares it to the stored baseline screenshot
- Generates a visual diff highlighting any differences
- Fails the test if differences exceed a configurable threshold
The comparison happens at the full page level. Ghost Inspector uses pixel-by-pixel comparison with a configurable sensitivity threshold to filter out antialiasing and minor rendering differences.
Enabling Screenshot Comparison
In the test settings, enable Screenshot Comparison. On the first run after enabling, Ghost Inspector establishes a baseline. Subsequent runs compare against that baseline.
Managing the Baseline
The baseline is updated manually when you intentionally change the UI. In the test results view, click Update Screenshot to set the current screenshot as the new baseline. This is the correct workflow for handling planned UI changes — you review the diff, confirm it's intentional, then update the baseline.
Handling Dynamic Content
Screenshot comparison breaks if your page has dynamic content: timestamps, rotating banners, personalized greetings, ads. Ghost Inspector handles this with ignore regions — rectangular areas of the screenshot that are excluded from comparison.
Configure ignore regions in the test editor by drawing rectangles over the dynamic areas. The comparison then skips those pixels entirely.
Sensitivity Threshold
Adjust the comparison threshold to control how much pixel difference is tolerated before the assertion fails. The threshold is set as a percentage of the total pixels:
0%— exact match required (too strict for most real pages)0.1%— a reasonable default for stable UIs1%— tolerates some rendering variation across browsers
Start at 0.1% and adjust based on the false positive rate you see.
Custom JavaScript Assertions
For validations that don't fit the built-in assertion types, Ghost Inspector lets you run custom JavaScript in the browser context and assert on the result.
Assert JavaScript Expression
The Execute Script (Condition) step type runs JavaScript and fails the test if the expression returns falsy:
// Assert that a global variable has the expected value
return window.appState.userId !== null;// Assert that localStorage has a token set
return localStorage.getItem('auth_token') !== null;// Assert that the page has no console errors (via a global you've set)
return window.__consoleErrors.length === 0;More Complex JavaScript Validations
You can write multi-line JavaScript with full access to the DOM and browser APIs:
// Count elements matching a condition beyond simple CSS selectors
var prices = Array.from(document.querySelectorAll('.product-price'));
var allPositive = prices.every(function(el) {
var price = parseFloat(el.textContent.replace('$', ''));
return price > 0;
});
return allPositive;// Verify a form field has correct validation state
var emailField = document.getElementById('email');
return emailField.validity.valid === true;// Check that an API response was stored in sessionStorage
var cached = sessionStorage.getItem('products');
if (!cached) return false;
var data = JSON.parse(cached);
return data.length > 0;The script must return a truthy value for the assertion to pass. Returning false, null, undefined, 0, or an empty string all count as failure.
Extracting Values with JavaScript
You can also use JavaScript to extract values and store them as test variables for use in later steps:
// Extract the order ID from the page and store it
return document.querySelector('.order-id').textContent.trim();This is the Execute Script (Extract) step type — it captures the return value and makes it available as a variable (e.g., {{orderID}}) in subsequent steps.
Cookie Assertions
Assert Cookie Exists
Verify that a cookie was set:
| Field | Value |
|---|---|
| Step Type | Assert Cookie Exists |
| Value | session_id |
Assert Cookie Value
Check the value of a specific cookie:
| Field | Value |
|---|---|
| Step Type | Assert Cookie Value |
| Cookie Name | user_preference |
| Value | dark_mode |
Cookie assertions are particularly useful for verifying authentication flows — checking that a session cookie is set after login and cleared after logout.
HTTP Response Assertions
Ghost Inspector can intercept and assert on HTTP requests made by the page. Under Test Settings, you can configure network assertions:
- Assert that a specific API endpoint was called
- Assert the HTTP status code of a response
- Assert that a response body contains specific content
This is useful for verifying that your UI correctly calls backend APIs when users perform actions.
Writing Effective Assertions
Assert outcomes, not implementation. Test what the user sees, not which CSS class is applied or which internal function ran. #welcome-message containing "Welcome, Jane" is a better assertion than .user-state-authenticated existing.
Assert both positive and negative. If you're testing that a form submission succeeds, assert the success message AND assert that the error message is absent.
Use specific selectors. Assertions on div or span without further specificity are fragile. Use IDs, data attributes, or ARIA roles: [data-testid="submit-btn"], [aria-label="Close dialog"].
Order assertions after interactions. Place assertions immediately after the action that should have caused the state change. Don't wait until the end of the test to assert on things that happened in the middle.
Keep JavaScript assertions simple. Complex JavaScript in assertions is hard to debug when it fails. If the logic gets complicated, break it into multiple simpler assertions.
The combination of built-in assertions for common cases and JavaScript for edge cases gives you the flexibility to test virtually any application behavior. The key is using the right assertion type for each situation rather than defaulting to JavaScript for everything.