How to Test Address Autocomplete: A Complete Guide
How to Test Address Autocomplete: A Complete Guide – Why It Matters
How to Test Address Autocomplete: A Complete Guide – Why It Matters
Address autocomplete is a high‑impact UI component that directly affects conversion, data quality, and user trust. When it fails, users abandon forms, enter invalid data, or encounter security risks such as injection via malformed suggestions. Testing this feature therefore validates that the underlying geocoding service, the front‑end debounce logic, and the accessibility layer all work together under real‑world conditions. A broken autocomplete can also expose internal APIs to scraping or reveal private address fragments, making security checks essential. In short, thorough testing guards against revenue loss, compliance violations, and brand damage.
How to Test Address Autocomplete: A Complete Guide – Test Matrix Overview
A systematic test matrix separates concerns into dimensions that can be automated, inspected manually, or validated through persona‑driven exploration. The table below lists the core categories, sub‑conditions, and recommended verification methods. Each row is mutually exclusive; combine them to achieve full coverage.
| Category | Sub‑condition | Expected outcome | Verification method |
|---|---|---|---|
| Happy path | Valid street, city, state, ZIP entered | Correct suggestion list appears, selection fills fields | UI assertion, API response check |
| Typing latency | User pauses 300 ms between keystrokes | Debounce triggers only after pause, no excess calls | Network timing, console log |
| Empty input | Field receives focus but no characters | No suggestions, placeholder remains | Visual check, ARIA live region |
| Whitespace only | User types spaces or tabs | Treated as empty, no suggestions | Same as empty input |
| Invalid characters | Input contains symbols (!@#$%^&*) | No suggestions or error tooltip | Tooltip validation, API 400 |
| Partial match | User types “123 Mai” expecting “123 Main St” | Suggestions contain matching street names | Result relevance scoring |
| Locale fallback | Input in unsupported language (e.g., Arabic) | Falls back to default language or shows “no results” | Language header, UI text |
| Network degradation | Simulated 3G latency or packet loss | Fallback to cached suggestions or clear error | Network throttling, UI state |
| Rate limiting | >5 requests/second from same IP | Service returns 429, UI shows retry message | Mock server, retry logic |
| Security injection | Input includes SQL or XSS payloads | No execution, sanitized suggestions | OWASP ZAP, manual inspection |
| Accessibility | Screen reader navigates suggestion list | Each item announces role, value, and keyboard hint | ARIA attributes, live region |
| Touch interaction | User taps suggestion on mobile | Selection closes keyboard, populates address fields | Gesture test, focus management |
| Keyboard navigation | Arrow keys move highlight, Enter selects | Focus moves logically, selection commits | Keystroke simulation |
| Duplicate suppression | Same address appears twice in data source | Only one instance shown in list | Deduplication check |
| International formats | Addresses with non‑US conventions (e.g., UK postcode) | Correct parsing and display per locale | Locale‑specific test data |
| Caching behavior | Repeated query after initial success | Second call served from cache, no extra latency | DevTools network tab, timestamps |
| Error handling | Geocoding service returns 500 | UI shows generic error, allows retry | Error boundary, fallback UI |
How to Test Address Autocomplete: A Complete Guide – Manual Testing Techniques
Manual testing remains valuable for exploratory scenarios, usability assessment, and edge‑case detection that automated scripts may miss due to static expectations. Begin with a baseline checklist: verify the component renders correctly on the target breakpoint, that the input field receives focus on page load, and that the placeholder text matches the design spec. Then execute the following steps, noting any deviation in a shared test‑run spreadsheet.
- Happy‑path validation – Type a known address (e.g., “742 Evergreen Terrace, Springfield, IL 62704”) slowly, pausing 200 ms between each character. Observe that after the third keystroke a dropdown appears, that the list narrows with each additional character, and that pressing Enter or clicking a suggestion fills all address sub‑fields (street, city, state, ZIP) without truncation.
- Debounce timing – Using a stopwatch, measure the interval between the final keystroke and the first network request. It should match the configured debounce (commonly 300 ms). Repeat with varying pause lengths (100 ms, 500 ms) to confirm the logic scales.
- Error states – Insert a known invalid pattern such as “!!!”. The component should either show no suggestions or display an inline error message (“Please enter a valid address”). Verify that the message disappears once valid input resumes.
- Accessibility audit – Activate a screen reader (NVDA on Windows, VoiceOver on macOS). Navigate to the input, then open the suggestion list via down arrow. Each item should be announced as “option,
, , ”. Ensure that pressing Escape closes the list and returns focus to the input. - Touch and gesture – On a physical device or emulator, tap the input to bring up the soft keyboard, type a few letters, then tap a suggestion. Confirm that the keyboard dismisses, the input loses focus, and the selected address populates the form. Repeat with a long‑press to ensure no context menu interferes.
- Network throttling – Use Chrome DevTools → Network → Throttling set to “Slow 3G”. Type an address and watch for a loading spinner or placeholder text. The UI should not freeze; if it does, note the blocking call.
- Rate‑limit simulation – Point the autocomplete endpoint to a local mock server (e.g., using
msworjson-server) that returns HTTP 429 after five rapid requests. Verify that the UI shows a retry‑after message and does not continue spamming requests. - Security probing – Paste a string containing
or' OR 1=1--. The response should treat the payload as plain text; no script execution or database error should appear. Use Burp Suite’s scanner to confirm no reflected XSS or SQLi. - Locale switching – Change the browser’s accepted language to
fr-FRand type a Canadian address (“900 Rue Saint‑Jacques, Montréal, QC H3C 1K1”). Suggestions should appear in French where applicable, and the postal code format should retain the space (H3C 1K1). - Duplicate detection – Load a test dataset that contains the same address twice (e.g., two entries for “1600 Pennsylvania Ave NW, Washington, DC 20500”). The dropdown must list it only once.
Document each step with screenshots or short video clips, and tag any failures with severity (P1 for crashes or data corruption, P2 for usability, P3 for cosmetic).
How to Test Address Autocomplete: A Complete Guide – Automated Testing Strategies
Automation provides repeatable regression guards and enables integration into CI pipelines. Choose a stack that matches the delivery platform: for web applications use Playwright or Cypress; for native Android use Espresso or UIAutomator2 via Appium; for hybrid apps combine both. The following patterns have proven effective across projects.
API‑level contract tests
Before exercising the UI, validate the backend endpoint directly. A typical contract includes:
- Request:
GET /autocomplete?q=123+Main&limit=5 - Response schema: array of objects each containing
place_id,description,matched_substrings(withoffsetandlength), and optionaltypes. - Status codes: 200 for valid queries, 400 for malformed input, 429 for throttling, 500 for server error.
Implement these checks with a library such as pact or dredd. Example in JavaScript using supertest:
const request = require('supertest');
const app = require('../src/app'); // express app
test('returns suggestions for valid query', async () => {
const res = await request(app)
.get('/autocomplete')
.query({ q: '123 Main', limit: 5 })
.expect(200);
expect(Array.isArray(res.body)).toBe(true);
expect(res.body.length).toBeGreaterThan(0);
expect(res.body[0]).toHaveProperty('description');
});
test('rejects non‑string query', async () => {
await request(app)
.get('/autocomplete')
.query({ q: 123 })
.expect(400);
});
Run this suite on every pull request; it catches contract drift before UI tests execute.
UI interaction tests with Playwright
Playwright offers auto‑waiting, network mocking, and tracing. A robust test suite covers happy path, debounce, accessibility, and error states.
// address-autocomplete.spec.js
const { test, expect } = require('@playwright/test');
test.describe('Address autocomplete component', () => {
test.beforeEach(async ({ page }) => {
await page.goto('https://example.com/checkout');
});
test('fills form after suggestion selection', async ({ page }) => {
const input = page.locator('#address-input');
await input.fill('742 Evergreen');
// Wait for dropdown to appear
const dropdown = page.locator('.autocomplete-suggestions');
await expect(dropdown).toBeVisible({ timeout: 3000 });
// Choose first suggestion
await dropdown.locator('>> nth=0').click();
// Verify sub‑fields
await expect(page.locator('#street')).toHaveValue('742 Evergreen Terrace');
await expect(page.locator('#city')).toHaveValue('Springfield');
await expect(page.locator('#state')).toHaveValue('IL');
await expect(page.locator('#zip')).toHaveValue('62704');
});
test('debounce limits network calls', async ({ page }) => {
await page.route('**/autocomplete', route => {
// Count calls
route.request().then(() => {
global.callCount = (global.callCount || 0) + 1;
});
return route.continue();
});
const input = page.locator('#address-input');
// Type fast, no pause
await input.type('123 Main St', { delay: 0 });
// Wait a bit for debounce to settle
await page.waitForTimeout(800);
expect(global.callCount).toBeLessThanOrEqual(1);
});
test('screen reader announces suggestions', async ({ page }) => {
await page.evaluate(() => {
// Inject axe core for accessibility checks
const script = document.createElement('script');
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/axe-core/4.7.2/axe.min.js';
document.head.appendChild(script);
});
await page.waitForFunction(() => window.axe);
const results = await page.evaluate(async () => {
return await axe.run();
});
expect(results.violations).toHaveLength(0);
});
test('shows error on malformed input', async ({ page }) => {
const input = page.locator('#address-input');
await input.fill('!!!');
const error = page.locator('.autocomplete-error');
await expect(error).toHaveText(/Please enter a valid address/i);
await input.fill('742 Evergreen');
await expect(error).toBeHidden();
});
});
Key points:
- Use `page.waitForTimeout only when testing.
- Mock the exact shape required by UI tests; this isolates front‑end logic.
- Run tests in headed mode occasionally to verify focus management and keyboard navigation.
Mobile automation with Appium (Android)
For native Android, the same logic applies but the locator strategy shifts to resource‑ids or content‑descriptions. Example in Java:
@Test
public void testAutocompleteSelection() {
AndroidElement input = (AndroidElement) driver.findElement(By.id("address_input"));
input.sendKeys("1600 Penn");
// Wait for suggestion list
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
List<AndroidElement> suggestions = wait.until(
ExpectedConditions.visibilityOfAllElementsLocatedBy(By.id("suggestion_item"))
);
assertFalse(suggestions.isEmpty());
suggestions.get(0).click();
AndroidElement street = (AndroidElement) driver.findElement(By.id("street_field"));
assertEquals("1600 Pennsylvania Ave NW", street.getAttribute("text"));
}
Add a test that rotates the device to landscape and portrait to ensure the suggestion popup adapts to screen size changes.
Cross‑browser visual regression
Tools like Percy or Chromatic can capture screenshots of the autocomplete dropdown across Chrome, Firefox, Safari, and Edge. Commit a baseline after each UI change; the CI job fails if any pixel diff exceeds a threshold (commonly 0.1 %). This catches styling regressions that functional tests miss (e.g., z‑index causing the list to render behind a fixed header).
Integrating with CI
Place the API contract tests in the test/ unit stage, UI Playwright tests in the test/ integration stage, and Appium tests in a separate mobile stage. Use Docker images that include browsers (mcr.microsoft.com/playwright) and the Android emulator (budtmo/docker-android-x86-11.0). Publish test results as JUnit XML so that platforms like Jenkins, GitHub Actions, or GitLab can display trends.
How to Test Address Autocomplete: A Complete Guide – Accessibility and Security Checks
Beyond functional correctness, address autocomplete must satisfy WCAG 2.1 AA and resist common injection vectors. The following checklist consolidates both domains.
Accessibility (WCAG)
| Criterion | Test | Pass condition |
|---|---|---|
| 1.3.1 Info and Relationships | Inspect DOM: suggestion list has role="listbox" and each option role="option" | Roles present |
| 1.4.3 Contrast (Minimum) | Use axe or manual contrast checker on suggestion text vs. background | Contrast ratio ≥ 4.5:1 |
| 2.1.1 Keyboard | Tab to input, type, use ArrowDown/Up to navigate, Enter to select, Escape to close | Focus moves as expected, no trap |
| 2.4.7 Focus Visible | Ensure a visible outline appears on the highlighted suggestion | Outline ≥ 2 px, contrast ≥ 3:1 |
| 3.2.1 On Focus | Opening the dropdown does not change context (no page navigation) | URL stays same |
| 4.1.2 Name, Role, Value | Each suggestion option has accessible name (visible text) and value (underlying data) | Screen reader reads both |
| 4.1.3 Status Messages | When no results, an aria‑live region announces “No results found” | Live region present, polite |
Run axe-core as part of your Playwright test suite (see earlier snippet) and fail the build on any violation of severity ≥ moderate.
Security
Address autocomplete often proxies to a third‑party geocoding API; treat that endpoint as an untrusted source.
- Input sanitization – Ensure the client never sends raw user input directly to a backend that constructs SQL or LDAP queries. Use parameterized queries or an ORM.
- Output encoding – Suggestions are inserted into the DOM as text nodes, not HTML. Verify that any special characters (
<,>,&,",') are escaped if you ever render them viainnerHTML. - Rate limiting & API key protection – The frontend should never expose the raw API key. Use a proxy service that adds the key server‑side and enforces per‑IP quotas. Test by attempting to extract the key from bundle sources; it should be absent or obfuscated.
- Data leakage – Some services return structured data that includes latitude/longitude or internal place IDs. Confirm that the UI only displays the fields required for the form (street, city, state, ZIP) and does not log or store the full payload unnecessarily.
- CORS misconfiguration – If the autocomplete endpoint is hosted on a different subdomain, verify that the server sends
Access-Control-Allow-Originlimited to your domain(s), not a wildcard. - Cache poisoning – Ensure that caching keys incorporate the full query string (including language and region parameters). Try to poison the cache with a malicious query that returns a script; the cached response should not be served to other users.
A quick manual security test: open DevTools, disable cache, set a breakpoint on the fetch to /autocomplete, and modify the request URL to include ?q=. Observe the network response; it should either return a 400 error or a sanitized array where the description field contains the literal string, not executable markup.
How to Test Address Autocomplete: A Complete Guide – Edge Cases That Appear Only in Production
Certain defects surface only under real‑world load, regional variations, or long‑term data drift. Anticipating them reduces post‑release fire drills.
1. International address formats
Production traffic may include addresses from countries where the postal code precedes the city, or where the state field is absent (e.g., Ireland). Your component must not assume a fixed order. Test with datasets from the Universal Postal Union (UPU) that contain:
- UK: “Flat 1, 22B Acacia Road, London, NW1 6XE”
- Japan: “〒100-0005 東京都千代田区丸の内1‑1‑1”
- Brazil: “Av. Paulista, 1578 – Bela Vista, São Paulo – SP, 01310‑200”
Validate that the suggestion list respects the local ordering and that the form fields map correctly (some countries may leave the state field blank).
2. Language‑specific tokenization
Autocomplete services often tokenize on spaces. In languages without spaces (Thai, Japanese, Chinese) the service relies on dictionary segmentation. If your backend does not pass the appropriate language parameter, suggestions may be garbled. Test by setting the Accept-Language header to th-TH and entering a Thai address (“ถนนพระรามที่ 1”). Confirm that the returned suggestions are legible and that the UI can display complex glyphs without font fallback issues.
3. Real‑time data updates
Geocoding databases are refreshed nightly. A newly constructed building may not appear in the sandbox dataset but will appear in production after the sync. Conversely, a demolished building may still be present in the cache, causing users to select an invalid address. Implement a “stale data” detection: if the place_id returned is not present in your internal address validation service, flag it for review. In test, mock the service to return a known‑bad place_id and verify the UI shows a warning (“This address may not be accurate”).
4. Network partitioning and CDN failover
Large‑scale outages can cause the autocomplete service to be unreachable from certain regions while still reachable from others. Use a service mesh simulator (e.g., Toxiproxy) to introduce 5% packet loss and 200 ms latency for a subset of requests. Ensure the UI degrades gracefully: show a placeholder, allow manual entry, and retry after back‑off.
5. Browser extensions that modify the DOM
Ad blockers or password managers sometimes inject elements into the autocomplete container, breaking layout or intercepting keyboard events. Test with popular extensions (uBlock Origin, LastPass) enabled. Verify that the suggestion list still appears, that focus is not stolen, and that no extra ARIA roles are added incorrectly.
6. Long‑running sessions and memory leaks
In single‑page applications, the autocomplete component may be instantiated multiple times as users navigate between views. If each instance retains references to the previous suggestion list or event listeners, memory grows. Use Chrome’s Memory panel to take a heap snapshot before and after a sequence of 50 navigations that involve the autocomplete. Assert that the delta in detached DOM nodes is less than a threshold (e.g., 5 nodes).
7. Edge‑case Unicode
Users may copy‑paste addresses containing zero‑width spaces (U+200B), directional marks (U+200E/U+200F), or emojis. These characters can break matching logic or cause the input width to miscalculate. Paste a string like “123\u200B Main St” and ensure the component treats it as “123 Main St” for matching, while still displaying the zero‑width character if the UI chooses to preserve it.
8. Concurrency race conditions
When a user types rapidly, multiple requests may be in flight simultaneously. If the UI updates the suggestion list based on the *last* response only, an out‑of‑order response can temporarily show stale data. Simulate this with a mock server that delays the second request by 150 ms while the first resolves instantly. Verify that the final list corresponds to the query with the most recent characters, not an earlier one.
9. Fallback to cached results when offline
Some applications cache the last N successful queries for offline use. Test by disabling the network, then typing a previously successful query; the cached list should appear. Then type a novel query; the UI should indicate “No results – check your connection”. Ensure that the cache does not serve stale data after the online service returns a different result for the same query (e.g., after a map update).
10. Legal and compliance constraints
Certain jurisdictions restrict the display of precise geolocation data for privacy reasons (e.g., GDPR’s “data minimization”). Confirm that the autocomplete never returns latitude/longitude beyond the granularity needed for the address fields. Review the service’s data processing agreement and log any instances where extra fields are inadvertently stored.
How to Test Address Autocomplete: A Complete Guide – Using Autonomous Exploration (SUSA)
Traditional scripted tests excel at verifying known paths but can miss emergent behaviors that arise from real user variability. Autonomous QA platforms like SUSATest address this gap by exploring the application without pre‑written scripts, using persona‑driven agents that mimic curious, impatient, novice, adversarial, elderly, accessibility, and power‑user behaviors. When pointed at a URL or fed an APK, SUSA performs the following steps relevant to address autocomplete:
- Surface discovery – The agent identifies every input field that resembles an address (by placeholder text, aria‑label, or proximity to city/state/ZIP fields). It then treats each as a candidate for autocomplete probing.
- Persona‑driven input generation – For each persona, SUSA synthesizes realistic input sequences. A curious user types slowly, exploring suggestions; an impatient user pastes a full address and hits Enter immediately; a novice user makes frequent typos and relies on suggestions to correct them; an adversarial user injects strings like
'; DROP TABLE users;--or long Unicode sequences to probe for injection or buffer overflows. - Dynamic observation – While the agent interacts, SUSA monitors network calls, DOM mutations, console errors, and accessibility events. It automatically flags:
- Missing or incorrect ARIA roles on the suggestion list.
- Excessive debounce leading to perceptible lag (> 300 ms).
- Unexpected HTTP status codes (429, 500) and whether the UI surfaces a helpful message.
- Focus traps where the keyboard cannot escape the suggestion list.
- Visual regressions detected via pixel‑diff against a baseline captured on a prior run.
- Cross‑session learning – After each run, SUSA stores a graph of visited screens and dead ends. On subsequent executions, it avoids re‑exploring paths that previously yielded no new information, thereby increasing coverage efficiency. This is especially valuable for address autocomplete because the number of possible query strings is vast; the platform learns which prefixes produce novel suggestions and prioritizes those.
- Report generation – At the end of a session, SUSA emits a JSON report that includes:
- A list of discovered UI elements with their associated selectors.
- A matrix of observed behaviors keyed by persona (e.g., “Impatient user – 3 attempts resulted in 429 errors”).
- Actionable bug reports with steps to reproduce, screenshots, and network traces.
- Regression‑ready scripts exported as Appium (Android) and Playwright (Web) code that can be checked into your repository.
To run SUSA against a staging build, install the CLI and point it at your URL:
npm install -g susatest-agent
susatest run \
--url https://staging.example.com/checkout \
--personas all \
--output ./susareport \
--export-playwright ./tests/generated \
--export-appium ./android/tests/generated
The --personas all flag activates the eight built‑in profiles. You can limit the set to curious,impatient,adversarial if you want to focus on exploratory and security‑oriented behavior. The generated Playwright scripts can be added to your CI pipeline as a supplemental regression suite, ensuring that any future change that alters the autocomplete flow is caught by both deterministic and exploratory tests.
How to Test Address Autocomplete: A Complete Guide – Checklist and Takeaways
Use this concise list before marking a story as done. Each item maps to a test category from the matrix; tick only after the corresponding evidence exists in your test repository.
- [ ] Happy‑path selection populates all address sub‑fields correctly.
- [ ] Debounce delay matches configuration (default 300 ms) and does not cause extra network calls on rapid typing.
- [ ] Empty or whitespace‑only input yields no suggestions and retains placeholder.
- [ ] Invalid characters trigger an inline error or empty list; no server error is returned.
- [ ] Partial match returns relevant suggestions sorted by relevance score.
- [ ] Locale‑specific input (language, address format) yields correctly localized suggestions.
- [ ] Network throttling shows a non‑blocking loading state and retries after back‑off.
- [ ] Rate‑limit responses (429) display a user‑friendly retry message and halt further requests.
- [ ] Security payloads (XSS, SQL) are treated as plain text; no execution or error leakage occurs.
- [ ] Screen reader announces each suggestion with role, value, and keyboard hint.
- [ ] Keyboard navigation (ArrowDown/Up, Enter, Escape) moves focus logically and closes the list on Escape.
- [ ] Touch selection dismisses the soft keyboard and updates the form without leaving focus trapped.
- [ ] Duplicate addresses in the data source appear only once in the suggestion list.
- [ ] International address structures (different element order, missing state) are handled without forcing US‑centric fields.
- [ ] Zero‑width or directional Unicode characters do not break matching or layout.
- [ ] Stale or missing place IDs trigger a warning or fallback to manual entry.
- [ ] Cached results are used only when offline and are invalidated after a successful online response.
- [ ] No memory leak: detached DOM nodes and event listeners do not accumulate over repeated navigations.
- [ ] Visual regression threshold is under 0.1 % across supported browsers.
- [ ] Accessibility audit (axe‑core) reports zero violations of moderate or higher severity.
- [ ] Security scan (OWASP ZAP or equivalent) reports no reflected XSS, SQLi, or information disclosure.
Takeaways
Address autocomplete is a deceptively simple widget that couples front‑end state management, backend service contracts, accessibility, and security. A layered testing strategy—starting with contract tests, augmenting with deterministic UI automation, and finishing with persona‑driven autonomous exploration—covers both the predictable and the surprising paths that users traverse. Prioritize the matrix categories that have historically caused production incidents in your organization (often debounce timing, locale handling, and error‑state messaging). Treat the checklist as a living document; add new items whenever a defect escapes to production, and retire those that have become invariant through robust tooling. By combining rigorous manual scrutiny, automated regression, and the adaptive coverage offered by platforms like SUSATest, you ship an address autocomplete component that feels instant, works for every user, and resists both functional and security regressions.
Test Your App Autonomously
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.
Try SUSA Free