QA How-To
Writing test cases for a login page (2026)
Learn writing test cases for a login page across functional, security, accessibility, session, recovery, API, and automation risks with practical 2026 examples.
15 min read | 3,033 words
TL;DR
Writing test cases for a login page starts with risk, controlled preconditions, explicit actions, and independently verifiable expected results. Cover the normal path, failure paths, state changes, recovery, and evidence needed for fast diagnosis.
Key Takeaways
- Model login as an identity and session workflow, not a two-field form.
- Cover success, rejection, recovery, lockout, throttling, and federation paths.
- Test privacy-safe errors without sacrificing useful recovery.
- Verify cookies, redirects, logout, renewal, and multi-tab session behavior.
- Include keyboard, zoom, screen reader, and accessible authentication checks.
- Automate stable high-value paths and keep exploratory abuse testing in scope.
Writing test cases for a login page is the practical process of turning product risk into observable, repeatable evidence. This guide shows working QA and SDET engineers how to plan coverage, execute it consistently, and communicate results that a delivery team can act on.
The goal is not a larger checklist. It is a defensible test approach that connects user impact, system behavior, and clear expected results. The examples are version-aware for 2026 and avoid assumptions that belong to a specific organization.
TL;DR
Writing test cases for a login page starts with risk, controlled preconditions, explicit actions, and independently verifiable expected results. Cover the normal path, failure paths, state changes, recovery, and evidence needed for fast diagnosis.
| Area | Positive case | Negative or edge case |
|---|---|---|
| Credentials | Valid active account | Wrong, unknown, locked, disabled |
| Session | Cookie accepted | Expired, revoked, multi-tab |
| Recovery | Valid unused link | Expired, reused, replaced |
| Federation | Valid provider response | Cancel, missing claim, provider error |
1. Model Login as a Trust Boundary: writing test cases for a login page
A login page verifies identity, establishes a session, redirects safely, and communicates failure without leaking sensitive information. Its risk extends to recovery, registration, federation, multi-factor authentication, rate limits, cookies, and logout. Treating it as two fields misses most defects.
Map actors, identity providers, session stores, devices, protected routes, and recovery channels. Record security requirements with the product and security teams rather than inventing controls during test execution.
For model login as a trust boundary, define the expected evidence before execution. Record the starting state, action, observable result, and user or system consequence. This keeps writing test cases for a login page grounded in decisions rather than a checklist of clicks. Review the case with the people who own requirements and implementation, especially when policy or architecture changes the correct outcome.
2. Define Preconditions and Test Accounts
Create controlled accounts for active, unverified, disabled, locked, expired-password, multi-factor, federated, and role-specific states. Give each test ownership and cleanup rules. Never use real customer credentials or shared production passwords.
Document browser state, existing cookies, original destination, feature flags, and identity-provider availability. A clean browser and an already authenticated browser should produce intentionally different results.
For define preconditions and test accounts, define the expected evidence before execution. Record the starting state, action, observable result, and user or system consequence. This keeps writing test cases for a login page grounded in decisions rather than a checklist of clicks. Review the case with the people who own requirements and implementation, especially when policy or architecture changes the correct outcome.
3. Write Core Functional Login Test Cases
Cover valid credentials, incorrect password, unknown identifier, blank and malformed inputs, keyboard submission, leading or trailing whitespace policy, case rules, remember-me behavior, and post-login redirect. Verify the resulting identity and authorization, not only a dashboard URL.
Test errors returned by both client and server. Disable JavaScript only if supported. Confirm repeated submission cannot create inconsistent state and that refresh does not resubmit credentials.
For write core functional login test cases, define the expected evidence before execution. Record the starting state, action, observable result, and user or system consequence. This keeps writing test cases for a login page grounded in decisions rather than a checklist of clicks. Review the case with the people who own requirements and implementation, especially when policy or architecture changes the correct outcome.
4. Test Validation and Privacy-Safe Error Handling
Validation should be clear, associated with fields, and preserve safe input. Authentication responses should avoid unnecessary account enumeration while still helping legitimate users recover. Compare messages, status codes, response shapes, and timing cautiously under approved security scope.
Check unexpected characters and long input for robust handling, not as a substitute for authorized security testing. Confirm logs and analytics do not store passwords, one-time codes, tokens, or full sensitive identifiers.
For test validation and privacy-safe error handling, define the expected evidence before execution. Record the starting state, action, observable result, and user or system consequence. This keeps writing test cases for a login page grounded in decisions rather than a checklist of clicks. Review the case with the people who own requirements and implementation, especially when policy or architecture changes the correct outcome.
5. Cover Password Recovery and Account Lifecycle
Test request, delivery, expiry, single use, replacement, cancellation, and successful reset. Verify old sessions and old passwords according to policy. Exercise unverified, disabled, deleted, merged, and organization-removed accounts.
Recovery is part of authentication and often a weaker path. Confirm that links bind to the intended account, redirect only to approved locations, and fail safely after use or expiry.
For cover password recovery and account lifecycle, define the expected evidence before execution. Record the starting state, action, observable result, and user or system consequence. This keeps writing test cases for a login page grounded in decisions rather than a checklist of clicks. Review the case with the people who own requirements and implementation, especially when policy or architecture changes the correct outcome.
6. Test Multi-Factor and Federated Login
Cover enrollment, challenge selection, correct and incorrect codes, expiry, resend, backup codes, device trust, lost factor, and recovery. For SSO, test user cancellation, provider error, missing claims, state mismatch handling, account linking, and logout expectations.
Do not attempt to bypass controls outside authorized plans. Use provider sandboxes or mocks for deterministic error paths, then retain a small integration suite against the real test provider.
For test multi-factor and federated login, define the expected evidence before execution. Record the starting state, action, observable result, and user or system consequence. This keeps writing test cases for a login page grounded in decisions rather than a checklist of clicks. Review the case with the people who own requirements and implementation, especially when policy or architecture changes the correct outcome.
7. Verify Sessions, Cookies, Redirects, and Logout
Inspect session cookie attributes according to architecture, including Secure, HttpOnly, SameSite, path, domain, and expiry. Test renewal, idle and absolute timeout, multi-tab behavior, browser restart, password change, role change, and revoked access.
Protected routes should reject unauthenticated requests and preserve only safe intended destinations. Validate redirect targets against allowlists. Logout should invalidate the relevant session, clear local state, and make browser back behavior safe.
For verify sessions, cookies, redirects, and logout, define the expected evidence before execution. Record the starting state, action, observable result, and user or system consequence. This keeps writing test cases for a login page grounded in decisions rather than a checklist of clicks. Review the case with the people who own requirements and implementation, especially when policy or architecture changes the correct outcome.
8. Include Accessibility and Usability Cases
Navigate with keyboard, verify logical focus, visible indicators, labels, error associations, status announcements, zoom, reflow, and password-manager support. Do not block paste without a justified compliant approach. Test show-password controls for name, state, keyboard operation, and focus stability.
Use WCAG 2.2 for testers for criterion-level coverage and the usability testing guide to observe real recovery behavior.
For include accessibility and usability cases, define the expected evidence before execution. Record the starting state, action, observable result, and user or system consequence. This keeps writing test cases for a login page grounded in decisions rather than a checklist of clicks. Review the case with the people who own requirements and implementation, especially when policy or architecture changes the correct outcome.
9. Test the Authentication API
UI checks need API and protocol coverage. Verify accepted content types, schema validation, generic rejection, rate-limit behavior, token or cookie issuance, CORS policy where relevant, and no sensitive response data. Confirm authorization on a protected endpoint after login.
This Playwright test uses current request-context APIs and avoids logging secrets. Values come from test-only environment variables.
import { test, expect } from "@playwright/test";
test("login creates a session that can access the profile", async ({ request }) => {
const response = await request.post("http://localhost:3000/api/login", {
data: { email: process.env.QA_USER_EMAIL, password: process.env.QA_USER_PASSWORD }
});
expect(response.ok()).toBeTruthy();
const profile = await request.get("http://localhost:3000/api/me");
expect(profile.status()).toBe(200);
await expect(profile.json()).resolves.toMatchObject({ email: process.env.QA_USER_EMAIL });
});
For test the authentication api, define the expected evidence before execution. Record the starting state, action, observable result, and user or system consequence. This keeps writing test cases for a login page grounded in decisions rather than a checklist of clicks. Review the case with the people who own requirements and implementation, especially when policy or architecture changes the correct outcome.
10. Automate Stable Login Journeys
Automate a small set of high-value successes and failures at API and UI layers. Use accessible locators, isolated accounts, saved authentication state only when the test is not about login, and deterministic identity-provider stubs for rare errors. Never put credentials in source control or failure screenshots.
Keep security-abuse exploration, assistive technology review, and third-party recovery checks alongside automation. Use Playwright authentication patterns and API test case design for deeper implementation.
For automate stable login journeys, define the expected evidence before execution. Record the starting state, action, observable result, and user or system consequence. This keeps writing test cases for a login page grounded in decisions rather than a checklist of clicks. Review the case with the people who own requirements and implementation, especially when policy or architecture changes the correct outcome.
11. Build a Risk-Based Login Test Matrix: writing test cases for a login page
Organize coverage by account state, credential result, factor, device state, network or provider result, destination, and expected session. Use pairwise selection for ordinary combinations, then add explicit high-risk interactions such as locked federated users with stale local sessions.
Trace each case to a requirement or threat. Review it after identity architecture, cookie policy, provider configuration, or recovery behavior changes.
For build a risk-based login test matrix, define the expected evidence before execution. Record the starting state, action, observable result, and user or system consequence. This keeps writing test cases for a login page grounded in decisions rather than a checklist of clicks. Review the case with the people who own requirements and implementation, especially when policy or architecture changes the correct outcome.
Interview Questions and Answers
Q: What makes this testing approach effective?
I begin with risk, define observable expected behavior, control the starting state, and capture evidence that another engineer can review. I avoid adding cases only to increase counts. The result should support a release or design decision.
Q: How do you decide what to test first?
I prioritize user and business consequence, change scope, likelihood, detectability, recovery, and historical failures. I cover irreversible and security-sensitive outcomes before minor presentation differences. I document the reasoning so the team can challenge it.
Q: How do you keep tests reproducible?
I specify environment, preconditions, data, actions, and independent expected results. I remove hidden dependencies and verify the case from a clean state. For intermittent behavior, I record timing and occurrence evidence without claiming an unsupported rate.
Q: When should a test be automated?
I automate stable, valuable, repeatable checks with deterministic setup and a reliable oracle. I keep human judgment, exploratory discovery, and rapidly changing behavior outside brittle automation. I choose the lowest layer that exposes the risk and add end-to-end coverage only when integration matters.
Q: How do you handle unclear requirements?
I identify the ambiguity with concrete examples and user impact, then seek an explicit product decision. I can test consistency and current observable behavior, but I do not present my preference as a requirement. Once decided, I record the source and update coverage.
Q: What evidence do you save?
I save only evidence that proves the relevant state or behavior, such as a concise trace, response, screenshot, log excerpt, or data record. I include identifiers and timestamps when useful, sanitize sensitive information, and follow retention policy.
Q: How do you review test quality?
I check traceability to risk, independence, controlled setup, clear actions, strong oracles, diagnostic failure output, and maintainability. I also look for missing state, time, permission, dependency, and recovery conditions.
Common Mistakes
- Writing vague expected results that cannot be independently verified.
- Depending on shared accounts or unexplained test data.
- Confusing a large number of cases with meaningful risk coverage.
- Copying production secrets or personal data into evidence.
- Automating unstable behavior before clarifying the requirement.
- Ignoring cleanup, retries, and the state left after failure.
- Failing to update coverage after architecture or policy changes.
Mistakes become expensive when they hide uncertainty. During review, ask whether another tester can reproduce the setup, whether the expected result has a credible source, and whether the evidence proves the stated impact. Correct weak reports and tests before they become permanent regression noise.
Conclusion
Writing test cases for a login page works best when it starts with risk and ends with verifiable evidence. Use the models, examples, and review questions in this guide as a baseline, then adapt them to your product architecture, users, and policies.
Choose one current high-risk workflow, apply the approach, and review the result with engineering and product. That small feedback loop will improve both the immediate coverage and the team's shared understanding of quality.
Challenge the data model. Include absent, stale, duplicated, malformed, and unauthorized records where they affect the topic. State which fixture owns the data and how cleanup restores isolation. Evidence should distinguish a product failure from contamination left by an earlier run.
Review environment assumptions explicitly. Browser state, feature flags, locale, viewport, network policy, and deployment version can change the outcome. Record only variables that matter, but never leave a future investigator guessing which system produced the evidence.
Examine timing and ordering. Delayed responses, retries, expiration, simultaneous actions, and background work can expose behavior that a single synchronous path hides. Define the acceptable final state before execution so the oracle is not invented after results appear.
Inspect permissions at every boundary. A visible control does not prove authorization, and a hidden control does not prove the server rejects access. Use test roles with known grants, verify both response and persistent state, and avoid testing beyond the approved scope.
Consider dependency behavior beyond total success and total outage. Slow success, partial data, duplicate delivery, and a timeout after a committed write require distinct recovery expectations. Capture correlation identifiers when they help connect evidence across services.
Test recovery as a first-class outcome. After a failure, users should understand the state, preserve safe work, retry without duplication, or choose a supported alternative. Verify cleanup and durable state instead of stopping when an error message appears.
Evaluate observability with the scenario. Logs, metrics, traces, and user-facing messages should support diagnosis without exposing secrets. A test that proves failure but leaves operators unable to locate it identifies an operational quality gap worth discussing.
Review the oracle independently from the implementation. Requirements, domain rules, contracts, and approved designs are stronger sources than copying the production calculation into the test. When the source is ambiguous, record the decision needed instead of forcing a false pass or fail.
Keep the specification readable for someone outside the original conversation. Use concrete names, ordered actions, and one primary purpose. Link supporting cases instead of turning one scenario into a chain whose first failure hides every later assertion.
Plan regression depth according to the change. Retest the direct behavior, then inspect shared components, adjacent states, and downstream side effects. Broad coverage is useful only when each failure remains diagnostic and the suite can be maintained.
Use production learning responsibly. Incidents, support themes, and telemetry can reveal missed assumptions, but customer information must be sanitized. Translate the learning into synthetic fixtures and a stable model that can be reviewed without copying sensitive records.
End with a decision check. The result should tell the team whether a risk is controlled, a requirement is unclear, a defect is present, or more evidence is needed. If none of those decisions is possible, refine the setup or expected result before adding the case permanently.
Challenge the data model. Include absent, stale, duplicated, malformed, and unauthorized records where they affect the topic. State which fixture owns the data and how cleanup restores isolation. Evidence should distinguish a product failure from contamination left by an earlier run.
Review environment assumptions explicitly. Browser state, feature flags, locale, viewport, network policy, and deployment version can change the outcome. Record only variables that matter, but never leave a future investigator guessing which system produced the evidence.
Examine timing and ordering. Delayed responses, retries, expiration, simultaneous actions, and background work can expose behavior that a single synchronous path hides. Define the acceptable final state before execution so the oracle is not invented after results appear.
Inspect permissions at every boundary. A visible control does not prove authorization, and a hidden control does not prove the server rejects access. Use test roles with known grants, verify both response and persistent state, and avoid testing beyond the approved scope.
Consider dependency behavior beyond total success and total outage. Slow success, partial data, duplicate delivery, and a timeout after a committed write require distinct recovery expectations. Capture correlation identifiers when they help connect evidence across services.
Test recovery as a first-class outcome. After a failure, users should understand the state, preserve safe work, retry without duplication, or choose a supported alternative. Verify cleanup and durable state instead of stopping when an error message appears.
Evaluate observability with the scenario. Logs, metrics, traces, and user-facing messages should support diagnosis without exposing secrets. A test that proves failure but leaves operators unable to locate it identifies an operational quality gap worth discussing.
Review the oracle independently from the implementation. Requirements, domain rules, contracts, and approved designs are stronger sources than copying the production calculation into the test. When the source is ambiguous, record the decision needed instead of forcing a false pass or fail.
Keep the specification readable for someone outside the original conversation. Use concrete names, ordered actions, and one primary purpose. Link supporting cases instead of turning one scenario into a chain whose first failure hides every later assertion.
Plan regression depth according to the change. Retest the direct behavior, then inspect shared components, adjacent states, and downstream side effects. Broad coverage is useful only when each failure remains diagnostic and the suite can be maintained.
Use production learning responsibly. Incidents, support themes, and telemetry can reveal missed assumptions, but customer information must be sanitized. Translate the learning into synthetic fixtures and a stable model that can be reviewed without copying sensitive records.
Interview Questions and Answers
What makes this testing approach effective?
I begin with risk, define observable expected behavior, control the starting state, and capture evidence that another engineer can review. I avoid adding cases only to increase counts. The result should support a release or design decision.
How do you decide what to test first?
I prioritize user and business consequence, change scope, likelihood, detectability, recovery, and historical failures. I cover irreversible and security-sensitive outcomes before minor presentation differences. I document the reasoning so the team can challenge it.
How do you keep tests reproducible?
I specify environment, preconditions, data, actions, and independent expected results. I remove hidden dependencies and verify the case from a clean state. For intermittent behavior, I record timing and occurrence evidence without claiming an unsupported rate.
When should a test be automated?
I automate stable, valuable, repeatable checks with deterministic setup and a reliable oracle. I keep human judgment, exploratory discovery, and rapidly changing behavior outside brittle automation. I choose the lowest layer that exposes the risk and add end-to-end coverage only when integration matters.
How do you handle unclear requirements?
I identify the ambiguity with concrete examples and user impact, then seek an explicit product decision. I can test consistency and current observable behavior, but I do not present my preference as a requirement. Once decided, I record the source and update coverage.
What evidence do you save?
I save only evidence that proves the relevant state or behavior, such as a concise trace, response, screenshot, log excerpt, or data record. I include identifiers and timestamps when useful, sanitize sensitive information, and follow retention policy.
How do you review test quality?
I check traceability to risk, independence, controlled setup, clear actions, strong oracles, diagnostic failure output, and maintainability. I also look for missing state, time, permission, dependency, and recovery conditions.
Frequently Asked Questions
How detailed should a test case be?
Include enough detail for a competent teammate to reproduce the state, action, and expected result without oral explanation. Remove irrelevant navigation and repeated boilerplate.
Should every scenario be automated?
No. Automate when repetition, stability, value, and determinism justify maintenance. Keep exploratory and judgment-heavy checks manual.
How should test data be managed?
Use synthetic, owned, resettable data with clear lifecycle rules. Never embed production credentials or personal customer data.
What makes a strong expected result?
It is observable, specific, and derived independently from a requirement, contract, domain rule, or accepted product decision.
How are severity and priority different?
Severity describes impact, while priority reflects when the organization chooses to address it. Teams should record and discuss them separately.
When should tests be reviewed?
Review them before high-risk execution, after requirement or architecture changes, and when incidents reveal a missed assumption. Remove obsolete or redundant coverage.