How to Write Test Cases for Chat Functionality (With Examples)

How to Write Test Cases for Chat Functionality (With Examples)

May 11, 2026 · 18 min read · How-To Guides

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:

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:

FieldPurposeExample Content
IDUnique identifier for traceabilityTC‑CHAT‑001
TitleShort, readable summaryVerify that a text message sent from User A appears in User B’s chat window within 2 seconds
PreconditionsState that must be established before executionTwo users are logged in, connected to the same chat room, and have an active network connection
Test DataSpecific values or files used in the stepsMessage text: “Hello, world!”; User A ID: alice@example.com; User B ID: bob@example.com
StepsOrdered actions performed by the tester or automation script1. 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 ResultObservable outcome that determines pass/failThe message “Hello, world!” appears in User B’s chat view, timestamped, and the typing indicator disappears.
PostconditionsState to leave the system in (optional)Both users remain logged in; no error dialogs are shown.
PriorityRelative importance for schedulingP1 (critical)
Requirement IDLink to the specificationCHAT‑001
Automation FeasibilityIndicator if the case can be scriptedYes – 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.).

CategoryTypical Checks
Message Send/ReceiveBasic text, Unicode characters, line breaks, maximum allowed length.
Message PersistenceReload page, restart app, switch device, verify history.
Typing IndicatorIndicator appears when a user types, disappears after pause or send.
Read ReceiptsUnread badge updates correctly after viewing.
Media UploadImage, GIF, video, file attachment renders and can be downloaded.
PresenceOnline/offline status updates correctly on login/logout and network loss.
Bot InteractionBot receives commands, returns expected responses, handles unknown input gracefully.
Moderation ActionsAdmin can mute a user; muted user sees system message and cannot send.
AccessibilityScreen reader announces new messages; color contrast meets AA; keyboard focus moves to input after send.
Performance Under Load50 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.

CategoryExample Negative Scenarios
Input ValidationSending an empty message, sending only spaces, sending a message longer than the server limit (e.g., 10 KB).
Malformed PayloadsInjecting , SQL‑like strings, or excessive Unicode control characters.
Network InterruptionsDropping Wi‑Fi mid‑send, switching from 4G to airplane mode, then reconnecting.
Concurrency ConflictsTwo users attempting to delete the same message simultaneously.
Permission BypassA regular user trying to kick another user or change room settings.
Resource ExhaustionUploading a file that exceeds storage quota, sending many large attachments in rapid succession.
State InconsistencyLogging out while a message is in the process of being sent, then logging back in.
Localization EdgeSending a message in a right‑to‑left language when UI expects left‑to‑right; checking for truncation.
Accessibility FailureHiding the send button behind a non‑focusable element, causing keyboard users to be unable to send.
Error MessagingVerifying 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.

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:

  1. User provisioning – Create two or more test accounts via API or admin UI; assign known passwords and roles.
  2. Room creation – Generate a chat room with a unique identifier; set its type (public, private, moderated).
  3. 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.
  4. Network conditioning – Apply tools like tc on Linux, Network Link Conditioner on macOS, or Chrome DevTools throttling to simulate latency and packet loss.
  5. Mock services – If the chat relies on external APIs (e.g., file storage, third‑party moderation), spin up mock servers that return controllable responses.
  6. Logging and capture – Enable console logs, network logs, and, for mobile, logcat; configure test framework to store artifacts on failure.
  7. 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 \ LikelihoodRare (1)Unlikely (2)Possible (3)Likely (4)Almost Certain (5)
Critical (5)510152025
High (4)48121620
Medium (3)3691215
Low (2)246810
Trivial (1)12345

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:

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.

IDTitlePreconditionsTest DataStepsExpected ResultPriorityRequirement ID
TC‑CHAT‑001Send plain text messageTwo users logged in, same roomMsg: “Hello world!”1. User A types message 2. Press Enter 3. Switch to User B viewMessage appears in User B’s chat with correct timestampP1CHAT‑001
TC‑CHAT‑002Send maximum‑length messageSame as aboveMsg: 2000‑char string (all ‘a’)Same as TC‑001Message sent, displayed fully, no truncationP1CHAT‑001
TC‑CHAT‑003Send message exceeding limitSame as aboveMsg: 2001‑char stringSame as TC‑001Input blocked or error toast shown, message not sentP2CHAT‑001
TC‑CHAT‑004Send empty messageSame as aboveMsg: "" (empty)Same as TC‑001Send button disabled or error shownP2CHAT‑001
TC‑CHAT‑005Send message with only spacesSame as aboveMsg: " "Same as TC‑001Same as TC‑004P2CHAT‑001
TC‑CHAT‑006Send Unicode emojiSame as aboveMsg: "😀👍🏽🎉"Same as TC‑001Emoji renders correctly in both clientsP1CHAT‑001
TC‑CHAT‑007Send message with line breaksSame as aboveMsg: "Line1\nLine2\nLine3"Same as TC‑001Lines preserved, displayed as separate linesP1CHAT‑001
TC‑CHAT‑008Persistence after page reloadTwo users logged in, message sentMsg: "Persist test"1. Send message as User A 2. Reload page for User B 3. Verify chatMessage still visible after reloadP1CHAT‑002
TC‑CHAT‑009Persistence after app restart (mobile)Same as TC‑008, using mobile appMsg: "Restart test"1. Send message 2. Background app, kill process 3. Relaunch app 4. Navigate to roomMessage present in chat historyP1CHAT‑002
TC‑CHAT‑010Typing indicator appearsTwo users logged inN/A1. User A focuses input 2. Types at least one characterUser B sees typing indicator near User A’s nameP2CHAT‑003
TC‑CHAT‑011Typing indicator disappears after pauseSame as TC‑010N/A1. User A types "Hello" 2. Waits 2 seconds without further inputIndicator fades outP2CHAT‑003
TC‑CHAT‑012Read receipt updatesTwo users logged in, one unread messageMsg: "Read me"1. User A sends message 2. User B opens chat and scrolls to messageUnread badge on User B’s chat list disappears; read timestamp shownP2CHAT‑004
TC‑CHAT‑013Image upload and displayTwo users logged inFile: valid PNG 150 KB1. User A clicks attachment icon 2. Selects PNG 3. SendsImage appears as thumbnail in chat; clicking opens full‑size viewP1CHAT‑005
TC‑CHAT‑014File upload exceeding quotaSame as TC‑013File: 12 MB (limit 10 MB)Same as TC‑013Upload fails, error toast shown, no file in chatP2CHAT‑005
TC‑CHAT‑015Video attachment playsSame as TC‑013File: MP4 5 MB, 720pSame as TC‑013Video thumbnail shows play icon; tapping plays video inlineP1CHAT‑005
TC‑CHAT‑016Link preview generationSame as TC‑013Msg: "https://example.com"Same as TC‑001Message shows preview card with title, image, descriptionP2CHAT‑005
TC‑CHAT‑017Bot responds to commandBot user added to roomCmd: "/weather Paris"1. Any user types command 2. SendsBot posts a message with weather info for ParisP2CHAT‑006
TC‑CHAT‑018Bot ignores malformed commandSame as TC‑017Cmd: "/weathr" (typo)Same as TC‑017Bot does not respond or replies with “unknown command”P2CHAT‑006
TC‑CHAT‑019Admin can mute userAdmin and regular user in roomN/A1. Admin opens user menu 2. Selects Mute for regular user 3. ConfirmsMuted user sees system message “You have been muted”; send button disabledP1CHAT‑007
TC‑CHAT‑020Muted user cannot send messagesSame as TC‑019N/A1. Muted user attempts to type and sendInput remains disabled or send blocked; error toast appearsP1CHAT‑007
TC‑CHAT‑021Network loss during sendTwo users logged in, good linkMsg: "Loss test"1. User A types message 2. Disable network (Wi‑Fi off) 3. Press Send 4. Re‑enable networkMessage queued locally; sent automatically when connection restores; appears in User B’s viewP2CHAT‑008
TC‑CHAT‑022Concurrent messages from three usersThree users logged inMsgs: U1: “A”, U2: “B”, U3: “C” (sent within 200 ms)1. All three type and press Send almost simultaneously 2. Observe orderMessages appear in the order received by server; no loss or duplicationP1CHAT‑009
TC‑CHAT‑023Message ordering after out‑of‑order delivery (simulated)Two users logged inMsgs: “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 delayP2CHAT‑009
TC‑CHAT‑024Accessibility – screen reader announces new messageUser with screen reader enabledMsg: "SR test"1. User A sends message 2. Listen to screen reader outputScreen reader reads “New message: SR test”P1CHAT‑010
TC‑CHAT‑025Keyboard focus returns to input after sendAny logged‑in userMsg: "Focus test"1. Focus on message input 2. Type text 3. Press EnterFocus returns to input field, ready for next messageP2CHAT‑010
TC‑CHAT‑026Large emoji sequence (ZWJ) rendersSame as TC‑006Msg: "👩‍🚀👨‍🚀👧‍👦" (family emojis)Same as TC‑006Sequence displays as single glyph where supported, fallback otherwiseP2CHAT‑001
TC‑CHAT‑027Message with HTML escaped correctlySame as TC‑001Msg: "Bold"Same as TC‑001Text shows literally "Bold" (no bold formatting)P1CHAT‑001
TC‑CHAT‑028Message with SQL‑like string does not affect DBSame as TC‑001Msg: "'; DROP TABLE messages; --"Same as TC‑001Message stored as plain text; no error, table intactP1CHAT‑001
TC‑CHAT‑029Rate limiting – too many messages in short timeOne user logged inMsg: "Spam" (send 30 times in 5 sec)1. Rapidly send message via script or toolAfter threshold, server returns 429; client shows “Too many requests, try later”P2CHAT‑011
TC‑CHAT‑030Language switch mid‑chatTwo users logged in, UI language toggleN/A1. Send a few messages in English 2. Switch UI language to Spanish 3. Continue chattingAll newly sent/received messages display correctly; UI labels in Spanish; previous messages unchangedP2CHAT‑012

How to use the table

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.

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:

  1. 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.
  2. 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.
  3. 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.
  4. 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:

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