How to Write Test Cases for Chat Functionality (With Examples)
How to Write Test Cases for Chat Functionality (With Examples)
How to Write Test Cases for Chat Functionality (With Examples)
Writing effective test cases for chat functionality requires a clear understanding of the feature’s behavior, the ways users interact with it, and the failure modes that can appear only under load or with unexpected input. This guide walks you through the full process—from defining scope and anatomy of a test case to building a concrete matrix of 20+ examples, prioritizing effort, and linking manual cases to autonomous exploration. By the end you will have a ready‑to‑use checklist, sample tables, and snippets you can adapt to your own project.
How to Write Test Cases for Chat Functionality (With Examples): Defining the Scope
Chat features vary from simple peer‑to‑peer text boxes to rich, multi‑user rooms with media, typing indicators, read receipts, bots, and moderation controls. Before writing any test, list the observable outcomes that stakeholders consider correct:
- Message delivery – a sent message appears in the recipient’s view within an expected latency window.
- Persistence – messages survive a page reload, app restart, or device switch when storage is enabled.
- Concurrency – multiple users can send and receive messages without losing ordering or duplicating content.
- Media handling – images, videos, files, and attachments render correctly and can be downloaded.
- System events – typing indicators, presence updates, read receipts, and connection‑status banners behave as specified.
- Moderation – profanity filters, mute/kick actions, and admin overrides produce the expected UI state.
- Accessibility – screen‑reader announcements, contrast ratios, and keyboard navigation meet WCAG 2.1 AA.
- Security – injection attempts, XSS payloads, and oversized messages are sanitized or rejected.
Write each of these as a separate requirement ID (e.g., CHAT‑001, CHAT‑002) and keep them in a traceability matrix. This matrix becomes the backbone for test‑case prioritization later.
How to Write Test Cases for Chat Functionality (With Examples): Test‑Case Anatomy
A well‑structured test case contains the following fields, each serving a distinct purpose during review, execution, and maintenance:
| Field | Purpose | Example Content |
|---|---|---|
| ID | Unique identifier for traceability | TC‑CHAT‑001 |
| Title | Short, readable summary | Verify that a text message sent from User A appears in User B’s chat window within 2 seconds |
| Preconditions | State that must be established before execution | Two users are logged in, connected to the same chat room, and have an active network connection |
| Test Data | Specific values or files used in the steps | Message text: “Hello, world!”; User A ID: alice@example.com; User B ID: bob@example.com |
| Steps | Ordered actions performed by the tester or automation script | 1. Log in as User A. 2. Navigate to the chat room. 3. Type the message in the input box. 4. Press Enter. 5. Switch to User B’s session. |
| Expected Result | Observable outcome that determines pass/fail | The message “Hello, world!” appears in User B’s chat view, timestamped, and the typing indicator disappears. |
| Postconditions | State to leave the system in (optional) | Both users remain logged in; no error dialogs are shown. |
| Priority | Relative importance for scheduling | P1 (critical) |
| Requirement ID | Link to the specification | CHAT‑001 |
| Automation Feasibility | Indicator if the case can be scripted | Yes – Playwright test. |
Keep the wording of each field concise but complete. Ambiguity in steps or expected results leads to flaky tests and missed defects.
How to Write Test Cases for Chat Functionality (With Examples): Positive Test Cases
Positive cases verify that the chat works as intended under normal conditions. They form the baseline confidence that the core flows are solid. Below are representative categories; each can be expanded with variations (different languages, emojis, etc.).
| Category | Typical Checks |
|---|---|
| Message Send/Receive | Basic text, Unicode characters, line breaks, maximum allowed length. |
| Message Persistence | Reload page, restart app, switch device, verify history. |
| Typing Indicator | Indicator appears when a user types, disappears after pause or send. |
| Read Receipts | Unread badge updates correctly after viewing. |
| Media Upload | Image, GIF, video, file attachment renders and can be downloaded. |
| Presence | Online/offline status updates correctly on login/logout and network loss. |
| Bot Interaction | Bot receives commands, returns expected responses, handles unknown input gracefully. |
| Moderation Actions | Admin can mute a user; muted user sees system message and cannot send. |
| Accessibility | Screen reader announces new messages; color contrast meets AA; keyboard focus moves to input after send. |
| Performance Under Load | 50 concurrent users sending messages; latency stays under SLA. |
Each of these categories can be turned into one or more test cases by varying the preconditions (e.g., network speed, user role) and the test data.
How to Write Test Cases for Chat Functionality (With Examples): Negative Test Cases
Negative cases confirm that the system correctly rejects or handles invalid input and unexpected states. They often uncover security gaps, UI bugs, or poor error messaging.
| Category | Example Negative Scenarios |
|---|---|
| Input Validation | Sending an empty message, sending only spaces, sending a message longer than the server limit (e.g., 10 KB). |
| Malformed Payloads | Injecting , SQL‑like strings, or excessive Unicode control characters. |
| Network Interruptions | Dropping Wi‑Fi mid‑send, switching from 4G to airplane mode, then reconnecting. |
| Concurrency Conflicts | Two users attempting to delete the same message simultaneously. |
| Permission Bypass | A regular user trying to kick another user or change room settings. |
| Resource Exhaustion | Uploading a file that exceeds storage quota, sending many large attachments in rapid succession. |
| State Inconsistency | Logging out while a message is in the process of being sent, then logging back in. |
| Localization Edge | Sending a message in a right‑to‑left language when UI expects left‑to‑right; checking for truncation. |
| Accessibility Failure | Hiding the send button behind a non‑focusable element, causing keyboard users to be unable to send. |
| Error Messaging | Verifying that the UI shows a helpful toast when the server returns a 500 error, not a generic “something went wrong”. |
For each negative case, define the expected system reaction: either a clear validation error, a silent discard with log entry, or a graceful degradation (e.g., message queued for later delivery).
How to Write Test Cases for Chat Functionality (With Examples): Edge and Boundary Cases
Edge cases live at the limits of specifications and often reveal assumptions baked into the code. Boundary testing focuses on minimum and maximum values, while edge cases explore unusual combinations.
- Length boundaries – 0‑character message (should be rejected), 1‑character message (accepted), max‑length‑1, max‑length, max‑length+1 (rejected).
- Timestamp boundaries – Sending a message with a device clock set far in the past or future; verify that the server normalizes or rejects based on policy.
- Session boundaries – First message after login, last message before logout, message sent exactly when the session expires.
- Network latency boundaries – Simulate 5 ms LAN, 100 ms typical 4G, 3000 ms poor connection; observe timeout and retry behavior.
- Unicode boundaries – Emoji sequences (e.g., skin‑tone modifiers), surrogate pairs, combining characters, zero‑width joiner (ZWJ) sequences.
- Media boundaries – Zero‑byte file, file exactly at allowed size, file with disallowed extension but valid MIME type.
- State transition boundaries – Rapid toggling of online/offline status, rapid successive edits of a message (if edit feature exists).
Document each edge case with the exact numeric or character limit derived from the requirement spec. When the spec is silent, derive limits from architecture (e.g., database column size, API payload limit) and treat them as implicit requirements.
How to Write Test Cases for Chat Functionality (With Examples): Data Setup and Test Environment
Reliable test execution depends on reproducible data and environment preparation. Outline a setup script or checklist that can be run before each test suite:
- User provisioning – Create two or more test accounts via API or admin UI; assign known passwords and roles.
- Room creation – Generate a chat room with a unique identifier; set its type (public, private, moderated).
- Device/Emulator preparation – For mobile, install the app on a clean emulator or real device; clear cache and storage. For web, use a fresh browser profile.
- Network conditioning – Apply tools like
tcon Linux, Network Link Conditioner on macOS, or Chrome DevTools throttling to simulate latency and packet loss. - Mock services – If the chat relies on external APIs (e.g., file storage, third‑party moderation), spin up mock servers that return controllable responses.
- Logging and capture – Enable console logs, network logs, and, for mobile, logcat; configure test framework to store artifacts on failure.
- Cleanup – After each test, delete messages, reset user status, and remove temporary files to avoid cross‑test contamination.
A typical CI step might look like:
# Provision users via backend API
curl -X POST https://api.example.com/users -d '{"email":"alice@test.com","password":"Temp123!"}'
curl -X POST https://api.example.com/users -d '{"email":"bob@test.com","password":"Temp123!"}'
# Create a room and add both users
ROOM_ID=$(curl -s -X POST https://api.example.com/rooms -d '{"name":"test-room","type":"public"}' | jq -r .id)
curl -X POST https://api.example.com/rooms/$ROOM_ID/members -d '{"user_id":"alice@test.com"}'
curl -X POST https://api.example.com/rooms/$ROOM_ID/members -d '{"user_id":"bob@test.com"}'
# Run the test suite
npx playwright test chat-tests.spec.js
Adjust the commands to match your stack; the principle is to keep the setup deterministic and idempotent.
How to Write Test Cases for Chat Functionality (With Examples): Prioritization and Traceability
Not all test cases carry equal risk. Use a simple risk‑based matrix that combines impact (how severe a failure would be) and likelihood (how often the condition occurs in production). Assign each test case a score (e.g., 1‑5 for each axis) and compute a priority number.
| Impact \ Likelihood | Rare (1) | Unlikely (2) | Possible (3) | Likely (4) | Almost Certain (5) |
|---|---|---|---|---|---|
| Critical (5) | 5 | 10 | 15 | 20 | 25 |
| High (4) | 4 | 8 | 12 | 16 | 20 |
| Medium (3) | 3 | 6 | 9 | 12 | 15 |
| Low (2) | 2 | 4 | 6 | 8 | 10 |
| Trivial (1) | 1 | 2 | 3 | 4 | 5 |
Sort test cases by descending score; execute the top 20% first in each test cycle. Maintain a traceability link from each test case ID to the requirement ID(s) it validates. This enables impact analysis when a requirement changes: you can instantly see which tests need review.
How to Write Test Cases for Chat Functionality (With Examples): Manual vs. Automated Approaches
Manual exploratory testing excels at discovering usability issues, unexpected UI states, and context‑dependent bugs that scripted tests might miss. Automation shines for regression, performance, and data‑driven validation of deterministic logic. A balanced strategy uses both:
- Manual – Conduct session‑based testing with personas (e.g., impatient user who repeatedly taps send, elderly user who needs larger touch targets). Use checklists to cover accessibility, error‑message clarity, and visual regression.
- Automated – Encode positive and negative cases that have clear pass/fail criteria. Parameterize them with data sets (CSV, JSON) to cover boundary values efficiently. Run them on every commit in a CI pipeline.
- Hybrid – Use automation to set up preconditions (user login, room creation) then hand over to a manual tester for a short exploratory burst. Record the session with a tool like
screenrecor Playwright’s trace viewer for later review.
Example: Automated Positive Test in Playwright
// chat-message-send.spec.js
const { test, expect } = require('@playwright/test');
test.describe('Chat – basic message send/receive', () => {
test('User A sends a text message that User B sees', async ({ page }) => {
// Preconditions: two logged‑in users in same room
await page.context().addCookies([{ name: 'session', value: 'alice-token', url: 'https://chat.example.com' }]);
await page.goto('https://chat.example.com/room/abc123');
await page.fill('#message-input', 'Hello from Alice');
await page.press('#message-input', 'Enter');
// Switch context to User B
await page.context().clearCookies();
await page.context().addCookies([{ name: 'session', value: 'bob-token', url: 'https://chat.example.com' }]);
await page.goto('https://chat.example.com/room/abc123');
// Expected result
const lastMsg = page.locator('.chat-message').last();
await expect(lastMsg).toHaveText('Hello from Alice');
await expect(lastMsg).toBeVisible({ timeout: 5000 });
});
});
Example: Automated Negative Test for Length Boundary
test('Message exceeding max length is rejected', async ({ page }) => {
await page.context().addCookies([{ name: 'session', value: 'alice-token', url: 'https://chat.example.com' }]);
await page.goto('https://chat.example.com/room/abc123');
const longMsg = 'A'.repeat(2001); // assume limit is 2000 chars
await page.fill('#message-input', longMsg);
await page.press('#message-input', 'Enter');
const errorToast = page.locator('.toast-error');
await expect(errorToast).toContainText('Message too long');
});
These snippets illustrate how to encode preconditions, steps, and expected assertions in a maintainable way.
How to Write Test Cases for Chat Functionality (With Examples): Worked Test Matrix (20+ Cases)
Below is a concrete table that you can copy into a test‑management tool or spreadsheet. Each row follows the anatomy described earlier. Feel free to extend with additional data variations.
| ID | Title | Preconditions | Test Data | Steps | Expected Result | Priority | Requirement ID |
|---|---|---|---|---|---|---|---|
| TC‑CHAT‑001 | Send plain text message | Two users logged in, same room | Msg: “Hello world!” | 1. User A types message 2. Press Enter 3. Switch to User B view | Message appears in User B’s chat with correct timestamp | P1 | CHAT‑001 |
| TC‑CHAT‑002 | Send maximum‑length message | Same as above | Msg: 2000‑char string (all ‘a’) | Same as TC‑001 | Message sent, displayed fully, no truncation | P1 | CHAT‑001 |
| TC‑CHAT‑003 | Send message exceeding limit | Same as above | Msg: 2001‑char string | Same as TC‑001 | Input blocked or error toast shown, message not sent | P2 | CHAT‑001 |
| TC‑CHAT‑004 | Send empty message | Same as above | Msg: "" (empty) | Same as TC‑001 | Send button disabled or error shown | P2 | CHAT‑001 |
| TC‑CHAT‑005 | Send message with only spaces | Same as above | Msg: " " | Same as TC‑001 | Same as TC‑004 | P2 | CHAT‑001 |
| TC‑CHAT‑006 | Send Unicode emoji | Same as above | Msg: "😀👍🏽🎉" | Same as TC‑001 | Emoji renders correctly in both clients | P1 | CHAT‑001 |
| TC‑CHAT‑007 | Send message with line breaks | Same as above | Msg: "Line1\nLine2\nLine3" | Same as TC‑001 | Lines preserved, displayed as separate lines | P1 | CHAT‑001 |
| TC‑CHAT‑008 | Persistence after page reload | Two users logged in, message sent | Msg: "Persist test" | 1. Send message as User A 2. Reload page for User B 3. Verify chat | Message still visible after reload | P1 | CHAT‑002 |
| TC‑CHAT‑009 | Persistence after app restart (mobile) | Same as TC‑008, using mobile app | Msg: "Restart test" | 1. Send message 2. Background app, kill process 3. Relaunch app 4. Navigate to room | Message present in chat history | P1 | CHAT‑002 |
| TC‑CHAT‑010 | Typing indicator appears | Two users logged in | N/A | 1. User A focuses input 2. Types at least one character | User B sees typing indicator near User A’s name | P2 | CHAT‑003 |
| TC‑CHAT‑011 | Typing indicator disappears after pause | Same as TC‑010 | N/A | 1. User A types "Hello" 2. Waits 2 seconds without further input | Indicator fades out | P2 | CHAT‑003 |
| TC‑CHAT‑012 | Read receipt updates | Two users logged in, one unread message | Msg: "Read me" | 1. User A sends message 2. User B opens chat and scrolls to message | Unread badge on User B’s chat list disappears; read timestamp shown | P2 | CHAT‑004 |
| TC‑CHAT‑013 | Image upload and display | Two users logged in | File: valid PNG 150 KB | 1. User A clicks attachment icon 2. Selects PNG 3. Sends | Image appears as thumbnail in chat; clicking opens full‑size view | P1 | CHAT‑005 |
| TC‑CHAT‑014 | File upload exceeding quota | Same as TC‑013 | File: 12 MB (limit 10 MB) | Same as TC‑013 | Upload fails, error toast shown, no file in chat | P2 | CHAT‑005 |
| TC‑CHAT‑015 | Video attachment plays | Same as TC‑013 | File: MP4 5 MB, 720p | Same as TC‑013 | Video thumbnail shows play icon; tapping plays video inline | P1 | CHAT‑005 |
| TC‑CHAT‑016 | Link preview generation | Same as TC‑013 | Msg: "https://example.com" | Same as TC‑001 | Message shows preview card with title, image, description | P2 | CHAT‑005 |
| TC‑CHAT‑017 | Bot responds to command | Bot user added to room | Cmd: "/weather Paris" | 1. Any user types command 2. Sends | Bot posts a message with weather info for Paris | P2 | CHAT‑006 |
| TC‑CHAT‑018 | Bot ignores malformed command | Same as TC‑017 | Cmd: "/weathr" (typo) | Same as TC‑017 | Bot does not respond or replies with “unknown command” | P2 | CHAT‑006 |
| TC‑CHAT‑019 | Admin can mute user | Admin and regular user in room | N/A | 1. Admin opens user menu 2. Selects Mute for regular user 3. Confirms | Muted user sees system message “You have been muted”; send button disabled | P1 | CHAT‑007 |
| TC‑CHAT‑020 | Muted user cannot send messages | Same as TC‑019 | N/A | 1. Muted user attempts to type and send | Input remains disabled or send blocked; error toast appears | P1 | CHAT‑007 |
| TC‑CHAT‑021 | Network loss during send | Two users logged in, good link | Msg: "Loss test" | 1. User A types message 2. Disable network (Wi‑Fi off) 3. Press Send 4. Re‑enable network | Message queued locally; sent automatically when connection restores; appears in User B’s view | P2 | CHAT‑008 |
| TC‑CHAT‑022 | Concurrent messages from three users | Three users logged in | Msgs: U1: “A”, U2: “B”, U3: “C” (sent within 200 ms) | 1. All three type and press Send almost simultaneously 2. Observe order | Messages appear in the order received by server; no loss or duplication | P1 | CHAT‑009 |
| TC‑CHAT‑023 | Message ordering after out‑of‑order delivery (simulated) | Two users logged in | Msgs: “First”, “Second” (sent with artificial delay on second) | 1. User A sends “First” 2. Introduce 500 ms delay on “Second” 3. Send “Second” | Chat displays “First” then “Second” despite network delay | P2 | CHAT‑009 |
| TC‑CHAT‑024 | Accessibility – screen reader announces new message | User with screen reader enabled | Msg: "SR test" | 1. User A sends message 2. Listen to screen reader output | Screen reader reads “New message: SR test” | P1 | CHAT‑010 |
| TC‑CHAT‑025 | Keyboard focus returns to input after send | Any logged‑in user | Msg: "Focus test" | 1. Focus on message input 2. Type text 3. Press Enter | Focus returns to input field, ready for next message | P2 | CHAT‑010 |
| TC‑CHAT‑026 | Large emoji sequence (ZWJ) renders | Same as TC‑006 | Msg: "👩🚀👨🚀👧👦" (family emojis) | Same as TC‑006 | Sequence displays as single glyph where supported, fallback otherwise | P2 | CHAT‑001 |
| TC‑CHAT‑027 | Message with HTML escaped correctly | Same as TC‑001 | Msg: "Bold" | Same as TC‑001 | Text shows literally "Bold" (no bold formatting) | P1 | CHAT‑001 |
| TC‑CHAT‑028 | Message with SQL‑like string does not affect DB | Same as TC‑001 | Msg: "'; DROP TABLE messages; --" | Same as TC‑001 | Message stored as plain text; no error, table intact | P1 | CHAT‑001 |
| TC‑CHAT‑029 | Rate limiting – too many messages in short time | One user logged in | Msg: "Spam" (send 30 times in 5 sec) | 1. Rapidly send message via script or tool | After threshold, server returns 429; client shows “Too many requests, try later” | P2 | CHAT‑011 |
| TC‑CHAT‑030 | Language switch mid‑chat | Two users logged in, UI language toggle | N/A | 1. Send a few messages in English 2. Switch UI language to Spanish 3. Continue chatting | All newly sent/received messages display correctly; UI labels in Spanish; previous messages unchanged | P2 | CHAT‑012 |
How to use the table
- Copy the rows into your test‑case management system (e.g., TestRail, Zephyr).
- Adjust the Test Data column to match the exact limits defined in your spec (character counts, file sizes).
- Map each Requirement ID to the corresponding item in your specification document.
- Prioritize execution using the Priority column (P1 = run every build, P2 = run nightly, P3 = run weekly).
How to Write Test Cases for Chat Functionality (With Examples): Checklist for Chat Testing
Before you sign off a release, run through this concise checklist. It captures the most common failure points discovered in production chat systems.
- [ ] Basic send/receive works for plain text, Unicode, line breaks, and maximum length.
- [ ] Message persistence survives page reload, app restart, device switch, and network loss.
- [ ] Typing indicator appears/disappears with appropriate timing.
- [ ] Read receipts update correctly for single and group chats.
- [ ] Media (image, video, file, GIF) uploads, renders, and can be downloaded; rejected files show clear error.
- [ ] Link previews generate when supported and fall back gracefully.
- [ ] Bot understands valid commands, replies with expected format, and handles unknown input without crashing.
- [ ] Moderation (mute, kick, ban, role change) reflects instantly for all participants and persists across sessions.
- [ ] Network resilience – messages queue locally and transmit when connectivity returns; no duplicate sends.
- [ ] Concurrency – multiple simultaneous sends from different users preserve order and integrity.
- [ ] Security – HTML, SQL, script, and oversized payloads are sanitized or rejected; error messages do not leak stack traces.
- [ ] Accessibility – screen readers announce new messages, contrast ratios meet AA, all controls keyboard operable.
- [ ] Performance – under expected load (e.g., 50 concurrent users), latency stays below SLA (e.g., 2 seconds).
- [ ] Internationalization – UI language switches, right‑to‑left scripts display correctly, date/time formats adapt.
- [ ] Logging & monitoring – failed sends, validation errors, and moderation actions are logged with sufficient detail for troubleshooting.
Mark each item as pass/fail and attach evidence (screenshots, logs, video) for any failures.
How to Write Test Cases for Chat Functionality (With Examples): Leveraging Autonomous Exploration
Manual test case design gives you deterministic coverage, but production chat apps often exhibit surprising behavior only discovered through unscripted interaction. Autonomous QA platforms—such as SUSA—can complement your test suite by:
- Exploring the state space – The agent logs in with varied personas (curious, impatient, novice, adversarial, elderly, accessibility‑focused, power user) and performs taps, scrolls, types, and dialog handling without pre‑written scripts.
- Detecting regressions – By remembering previously visited screens and dead ends, each run builds a knowledge base; new runs highlight previously unseen paths or re‑introduced bugs.
- Generating regression artifacts – After a session, SUSA exports Appium (Android) or Playwright (Web) scripts that reproduce the discovered flows, which you can add to your CI pipeline.
- Providing persona‑specific insights – For example, the “impatient” persona may rapidly tap the send button, exposing double‑send bugs; the “accessibility” persona may trigger screen‑reader‑only issues.
How to run SUSA locally
# Install the agent (requires Python 3.8+)
pip install susatest-agent
# Point it at a web chat app
susatest run --url https://chat.example.com --personas curious impatient accessibility --output ./susareport
# Or test a mobile APK
susatest run --apk ./chat-app.apk --device emulator-5554 --personas power-user elderly --output ./susareport
The command produces a JSON report and a set of generated test scripts. Review the report for:
- Crashes or ANRs (Android) / unhandled promise rejections (Web).
- Dead UI elements – buttons that never respond to taps or clicks.
- Accessibility violations – missing labels, insufficient contrast, focus traps.
- UX friction – excessively long flows to send a message, confusing error modals.
You can then map any discovered issue back to a requirement (e.g., CHAT‑001) and, if needed, add a new manual test case to cover the gap.
How to Write Test Cases for Chat Functionality (With Examples): Closing Takeaways
Writing high‑signal test cases for chat functionality is a disciplined blend of specification‑driven design, risk‑based prioritization, and exploratory validation. Start by decomposing the feature into clear, testable requirements (message delivery, persistence, media, moderation, accessibility, security). For each requirement, craft test cases that follow a consistent anatomy—ID, title, preconditions, steps, expected result, postconditions, priority, and traceability. Populate a matrix that covers positive, negative, edge, and boundary scenarios; the worked example above provides a ready‑to‑use template you can extend.
Complement those manual cases with automated scripts for repetitive checks (length limits, validation, persistence) and integrate them into your CI pipeline. Use a simple impact‑likelihood matrix to decide which tests run on every commit and which can be deferred to nightly or weekly cycles. Finally, augment your effort with an autonomous exploration tool like SUSA to surface hidden regressions, persona‑specific problems, and generate regression scripts that keep your test suite current as the app evolves.
By following this guide, you will have a repeatable process that delivers confidence that your chat feature works correctly for all expected users, fails gracefully under abnormal conditions, and remains maintainable as the product grows. Happy testing.
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