Loading State Tester Skill
You are an expert QA automation engineer specializing in loading state verification, asynchronous UI behavior testing, and perceived performance analysis. When asked to test loading indicators, skeleton screens, progress bars, or any transitional UI states in a web application, follow these comprehensive instructions to systematically verify that every async operation provides appropriate user feedback.
Core Principles
-
Every Async Operation Needs Visual Feedback -- When a user triggers an action that takes more than 100 milliseconds, they must see immediate visual confirmation that the system is working. Silent waiting creates uncertainty: the user does not know whether they clicked the button, whether the request was sent, or whether the application has frozen.
-
Loading States Must Appear Instantly -- The loading indicator should appear within one animation frame of the triggering action, typically under 16 milliseconds. A delay between the user's click and the appearance of a spinner creates a perceptible gap that feels like the application is unresponsive.
-
Loading States Must Disappear Completely -- When data arrives or an error occurs, every loading indicator must be removed. Stale spinners that persist after content has loaded, or skeleton screens that remain visible beneath actual content, are severe UX bugs that erode user confidence.
-
Error States Must Replace Loading States -- When an async operation fails, the loading indicator must transition to an error state, not simply disappear. A spinner that vanishes with no content and no error message leaves the user stranded with no understanding of what happened.
-
Progressive Loading Beats All-or-Nothing -- When a page has multiple independent data sources, each section should show its own loading state and resolve independently. Holding the entire page behind a single spinner until every request completes makes the application feel slower than it actually is.
-
Skeleton Screens Preserve Layout Stability -- Skeleton screens prevent cumulative layout shift by reserving the exact space that content will occupy. A well-implemented skeleton matches the dimensions and structure of the loaded content so the page does not jump when data arrives.
-
Loading States Must Be Accessible -- Screen readers must announce loading states and their completion. Use aria-busy, aria-live regions, and role="status" to communicate state transitions to assistive technology users.
Project Structure
Organize your loading state test suite with this directory structure:
tests/
loading-states/
initial-page-load.spec.ts
navigation-transitions.spec.ts
form-submission-loading.spec.ts
infinite-scroll-loading.spec.ts
skeleton-screen-fidelity.spec.ts
error-state-transitions.spec.ts
concurrent-loading.spec.ts
fixtures/
throttled-network.fixture.ts
helpers/
loading-detector.ts
skeleton-validator.ts
timing-tracker.ts
accessibility-checker.ts
reports/
loading-state-audit.json
loading-state-audit.html
playwright.config.ts
Each spec file targets a different category of loading behavior. The fixtures directory provides network throttling utilities. Helpers contain detection logic for various loading indicator patterns.
Detailed Guide
Step 1: Build a Loading State Detector
The first challenge is reliably detecting loading indicators across different UI libraries and implementation patterns. Applications use spinners, skeleton screens, progress bars, shimmer effects, and opacity changes. Build a detector that recognizes all of these patterns.
import { Page, Locator } from '@playwright/test';
export interface LoadingIndicator {
type: 'spinner' | 'skeleton' | 'progress-bar' | 'shimmer' | 'overlay' | 'text' | 'opacity';
selector: string;
element: Locator;
appearedAt?: number;
disappearedAt?: number;
durationMs?: number;
page: string;
context: string;
}
export class LoadingDetector {
private indicators: LoadingIndicator[] = [];
private static readonly SPINNER_SELECTORS = [
'[role="progressbar"]',
'[aria-busy="true"]',
'.spinner',
'.loading-spinner',
'.animate-spin',
'.MuiCircularProgress-root',
'.chakra-spinner',
'[data-testid="loading-spinner"]',
,
,
];
= [
,
,
,
,
,
,
,
,
,
];
= [
,
,
,
,
,
,
];
= [
,
,
,
,
];
(: , : ): <[]> {
: [] = [];
startTime = performance.();
( selector .) {
locator = page.(selector);
count = locator.();
( i = ; i < count; i++) {
element = locator.(i);
( element.()) {
detected.({
: ,
selector,
element,
: startTime,
: page.(),
context,
});
}
}
}
( selector .) {
locator = page.(selector);
count = locator.();
( i = ; i < count; i++) {
element = locator.(i);
( element.()) {
detected.({
: ,
selector,
element,
: startTime,
: page.(),
context,
});
}
}
}
( selector .) {
locator = page.(selector);
count = locator.();
( i = ; i < count; i++) {
element = locator.(i);
( element.()) {
detected.({
: ,
selector,
element,
: startTime,
: page.(),
context,
});
}
}
}
( selector .) {
locator = page.(selector);
count = locator.();
( i = ; i < count; i++) {
element = locator.(i);
( element.()) {
detected.({
: ,
selector,
element,
: startTime,
: page.(),
context,
});
}
}
}
..(...detected);
detected;
}
(: , : = ): <> {
allSelectors = [
....,
....,
....,
....,
];
deadline = .() + timeoutMs;
(.() < deadline) {
anyVisible = ;
( selector allSelectors) {
locator = page.(selector);
count = locator.();
( i = ; i < count; i++) {
( locator.(i).()) {
anyVisible = ;
;
}
}
(anyVisible) ;
}
(!anyVisible) ;
page.();
}
();
}
(): [] {
[....];
}
}
Step 2: Build a Network Throttling Fixture
To test loading states reliably, you need to slow down network responses so loading indicators are visible long enough to verify. Without throttling, fast local development servers resolve requests so quickly that loading states flash for a single frame and are untestable.
import { test as base, Page, Route } from '@playwright/test';
interface ThrottleOptions {
latencyMs: number;
pattern?: string;
}
interface ThrottledFixtures {
throttledPage: Page;
setLatency: (options: ThrottleOptions) => Promise<void>;
setOffline: () => Promise<void>;
setOnline: () => Promise<void>;
simulateTimeout: (pattern: string, timeoutMs: number) => Promise<void>;
}
export const test = base.extend<ThrottledFixtures>({
throttledPage: async ({ page }, use) => {
await use(page);
},
setLatency: async ({ page }, use) => {
const setLatency = () => {
page.(pattern, (: ) => {
( (resolve, latencyMs));
route.();
});
};
(setLatency);
},
: ({ context }, use) => {
= () => {
context.();
};
(setOffline);
},
: ({ context }, use) => {
= () => {
context.();
};
(setOnline);
},
: ({ page }, use) => {
= () => {
page.(pattern, (: ) => {
( (resolve, timeoutMs));
route.();
});
};
(simulateTimeout);
},
});
Step 3: Test Initial Page Load States
The most visible loading state is the initial page load. Every page that fetches data on mount must show a loading indicator until data is ready.
import { test } from '../fixtures/throttled-network.fixture';
import { expect } from '@playwright/test';
import { LoadingDetector } from '../helpers/loading-detector';
test.describe('Initial Page Load States', () => {
test('dashboard shows loading indicators before data arrives', async ({
throttledPage: page,
setLatency,
}) => {
await setLatency({ latencyMs: 2000, pattern: '**/api/**' });
const detector = new LoadingDetector();
await page.goto('/dashboard', { waitUntil: 'domcontentloaded' });
const indicators = await detector.detectAll(page, 'dashboard-initial-load');
expect(indicators.length).toBeGreaterThan(0);
const types = (indicators.( i.));
(
types.() || types.() || types.()
).();
detector.(page);
afterLoad = detector.(page, );
stillVisible = afterLoad.(
i. !==
);
(stillVisible.).();
});
(, ({
: page,
setLatency,
}) => {
({ : , : });
page.(, { : });
skeletonBounds = page.( {
skeletons = .(
);
.(skeletons).( {
rect = el.();
{
: rect.,
: rect.,
: rect.,
: rect.,
};
});
});
page.();
page.();
contentBounds = page.( {
contentAreas = .(
);
.(contentAreas).( {
rect = el.();
{
: rect.,
: rect.,
: rect.,
: rect.,
};
});
});
(skeletonBounds. > && contentBounds. > ) {
( i = ; i < .(skeletonBounds., contentBounds.); i++) {
skeleton = skeletonBounds[i];
content = contentBounds[i];
widthDiff = .(skeleton. - content.) / content.;
heightDiff = .(skeleton. - content.) / content.;
(widthDiff).();
(heightDiff).();
}
}
});
(, ({
: page,
setLatency,
}) => {
({ : , : });
page.();
page.();
page.();
hasContent = page.( {
body = ...();
loadingOnlyPhrases = [, , ];
isOnlyLoading = loadingOnlyPhrases.(
body.() === phrase
);
body. > && !isOnlyLoading;
});
(hasContent).();
});
});
Step 4: Test Form Submission Loading States
Form submissions are critical interaction points where loading states directly affect the user's confidence that their action was received.
import { test } from '../fixtures/throttled-network.fixture';
import { expect } from '@playwright/test';
test.describe('Form Submission Loading States', () => {
test('submit button shows loading state and prevents double-submit', async ({
throttledPage: page,
setLatency,
}) => {
await setLatency({ latencyMs: 3000, pattern: '**/api/**' });
await page.goto('/contact');
await page.fill('[name="name"]', 'Test User');
await page.fill('[name="email"]', 'test@example.com');
await page.fill('[name="message"]', 'Test message content');
const submitButton = page.locator('button[type="submit"]');
const beforeText = await submitButton.textContent();
const beforeDisabled = await submitButton.isDisabled();
expect(beforeDisabled).();
submitButton.();
page.();
duringDisabled = submitButton.();
(duringDisabled).();
hasSpinner = submitButton.().();
buttonText = submitButton.();
textChanged = buttonText !== beforeText;
(hasSpinner > || textChanged).();
page.();
page.();
afterText = submitButton.();
isSuccess =
afterText?.().() ||
afterText?.().() ||
afterText?.().();
isReset = !( submitButton.());
(isSuccess || isReset).();
});
(, ({
: page,
}) => {
requestCount = ;
page.(, (route) => {
requestCount++;
( (resolve, ));
route.({ : , : .({ : }) });
});
page.();
page.(, );
page.(, );
page.(, );
submitButton = page.();
submitButton.();
page.();
submitButton.({ : });
page.();
submitButton.({ : });
page.();
(requestCount).();
});
(, ({
: page,
setLatency,
}) => {
({ : , : });
page.();
usernameInput = page.();
usernameInput.();
usernameInput.();
fieldContainer = usernameInput.();
hasFieldSpinner = fieldContainer
.()
.();
fieldText = fieldContainer.();
hasCheckingText =
fieldText?.().() ||
fieldText?.().();
(hasFieldSpinner > || hasCheckingText).();
});
});
Step 5: Test Error State Transitions from Loading
When an async operation fails, the loading indicator must transition cleanly to an error state.
import { test } from '../fixtures/throttled-network.fixture';
import { expect } from '@playwright/test';
import { LoadingDetector } from '../helpers/loading-detector';
test.describe('Loading to Error State Transitions', () => {
test('failed API replaces spinner with error message', async ({
throttledPage: page,
}) => {
await page.route('**/api/data**', async (route) => {
await new Promise((resolve) => setTimeout(resolve, 1500));
await route.fulfill({
status: 500,
contentType: 'application/json',
body: JSON.stringify({ error: 'Internal Server Error' }),
});
});
await page.goto('/dashboard', { waitUntil: 'domcontentloaded' });
const detector = new ();
loadingIndicators = detector.(page, );
(loadingIndicators.).();
page.();
postErrorIndicators = detector.(page, );
visibleLoading = [];
( ind postErrorIndicators) {
( ind..().( )) {
visibleLoading.(ind);
}
}
(visibleLoading.).();
errorVisible = page
.()
.()
.()
.( );
(errorVisible).();
});
(, ({
: page,
setOffline,
setOnline,
}) => {
page.();
page.();
();
refreshButton = page.();
( refreshButton.() > ) {
refreshButton.().();
page.();
pageContent = page.();
hasOfflineMessage =
pageContent?.().() ||
pageContent?.().() ||
pageContent?.().();
(hasOfflineMessage).();
}
();
});
(, ({
: page,
}) => {
callCount = ;
page.(, (route) => {
callCount++;
( (resolve, ));
(callCount === ) {
route.({
: ,
: ,
: .({ : }),
});
} {
route.({
: ,
: ,
: .({ : [{ : , : }] }),
});
}
});
page.(, { : });
page.();
retryButton = page.(
);
( retryButton.() > ) {
retryButton.().();
page.();
detector = ();
retryLoading = detector.(page, );
page.();
(callCount).();
}
});
});
Step 6: Test Infinite Scroll Loading
Infinite scroll patterns require a footer loading indicator that appears when the user scrolls near the bottom and disappears when new items load.
import { test } from '../fixtures/throttled-network.fixture';
import { expect } from '@playwright/test';
import { LoadingDetector } from '../helpers/loading-detector';
test.describe('Infinite Scroll Loading States', () => {
test('scrolling to bottom triggers loading indicator for next page', async ({
throttledPage: page,
setLatency,
}) => {
await setLatency({ latencyMs: 2000, pattern: '**/api/**page=2**' });
await page.goto('/feed');
await page.waitForLoadState('networkidle');
const initialItems = await page.locator('[data-testid="feed-item"]').count();
await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
await page.waitForTimeout();
detector = ();
indicators = detector.(page, );
hasBottomLoading = indicators.(
i. === || i. ===
);
(hasBottomLoading).();
page.();
afterItems = page.().();
(afterItems).(initialItems);
});
(, ({
: page,
}) => {
page.(, (route) => {
url = route.().();
pageNum = (url.()?.[] || );
( (resolve, ));
(pageNum > ) {
route.({
: ,
: ,
: .({ : [], : }),
});
} {
route.();
}
});
page.();
page.();
( i = ; i < ; i++) {
page.( .(, ..));
page.();
}
pageText = page.();
hasEndMessage =
pageText?.().() ||
pageText?.().() ||
pageText?.().() ||
pageText?.().();
detector = ();
finalIndicators = detector.(page, );
(finalIndicators.( i. === ).).();
});
});
Step 7: Test Concurrent Loading States
When multiple sections of a page fetch data independently, each section should manage its own loading state.
import { test } from '../fixtures/throttled-network.fixture';
import { expect } from '@playwright/test';
test.describe('Concurrent Independent Loading States', () => {
test('fast section loads while slow section still shows loading', async ({
throttledPage: page,
}) => {
await page.route('**/api/stats**', async (route) => {
await new Promise((resolve) => setTimeout(resolve, 500));
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ visitors: 1234, pageViews: 5678 }),
});
});
await page.route('**/api/activity**', async (route) => {
await new Promise((resolve) => setTimeout(resolve, ));
route.({
: ,
: ,
: .({ : [{ : , : }] }),
});
});
page.(, { : });
page.();
statsSection = page.();
activitySection = page.();
(( statsSection.()) > && ( activitySection.()) > ) {
statsHasSpinner = statsSection
.()
.();
(statsHasSpinner).();
activityHasSpinner = activitySection
.()
.();
(activityHasSpinner).();
}
});
});
Step 8: Check Accessibility of Loading States
import { Page } from '@playwright/test';
export interface LoadingA11yIssue {
element: string;
issue: string;
severity: 'critical' | 'major' | 'minor';
recommendation: string;
}
export class LoadingAccessibilityChecker {
async check(page: Page): Promise<LoadingA11yIssue[]> {
const issues: LoadingA11yIssue[] = [];
const busyCheck = await page.evaluate(() => {
const loadingEls = document.querySelectorAll(
'.loading, .spinner, [data-loading="true"], .skeleton, .animate-pulse'
);
return Array.from(loadingEls).map((el) => ({
tag: el.tagName.toLowerCase() + '.' + (el.className || ).()[],
: el.() === ,
: el.() !== ,
}));
});
( item busyCheck) {
(!item. && !item.) {
issues.({
: item.,
: ,
: ,
: ,
});
}
}
liveRegions = page.( {
regions = .();
regions.;
});
(liveRegions === ) {
issues.({
: ,
: ,
: ,
: ,
});
}
progressBars = page.( {
bars = .();
.(bars).( ({
: el.(),
: el.(),
: el.(),
: el.() || el.(),
}));
});
( bar progressBars) {
(!bar. || !bar.) {
issues.({
: ,
: ,
: ,
: ,
});
}
(!bar.) {
issues.({
: ,
: ,
: ,
: ,
});
}
}
issues;
}
}
Configuration
Playwright Configuration for Loading State Testing
import { defineConfig } from '@playwright/test';
export default defineConfig({
testDir: './tests/loading-states',
timeout: 60000,
retries: 1,
use: {
baseURL: process.env.BASE_URL || 'http://localhost:3000',
screenshot: 'on',
video: 'on-first-retry',
trace: 'on-first-retry',
},
reporter: [
['html', { open: 'never' }],
['json', { outputFile: 'reports/loading-state-results.json' }],
],
projects: [
{
name: 'loading-desktop',
use: { browserName: 'chromium' },
},
{
name: 'loading-mobile',
use: {
browserName: 'chromium',
viewport: { width: 375, height: 812 },
isMobile: true,
},
},
],
});
Timing Thresholds Configuration
export interface TimingThresholds {
loadingAppearanceMaxMs: number;
loadingMinVisibleMs: number;
loadingMaxVisibleMs: number;
skeletonToContentMaxShiftPx: number;
}
export const defaultThresholds: TimingThresholds = {
loadingAppearanceMaxMs: 100,
loadingMinVisibleMs: 200,
loadingMaxVisibleMs: 30000,
skeletonToContentMaxShiftPx: 20,
};
export class TimingTracker {
private entries: Array<{
context: string;
triggerTime: number;
loadingAppearedTime: number;
loadingDisappearedTime: number;
}> = [];
record(context: string, triggerTime: number, appearedTime: number, disappearedTime: number) {
this.entries.push({
context,
triggerTime,
: appearedTime,
: disappearedTime,
});
}
(: = defaultThresholds): [] {
: [] = [];
( entry .) {
appearanceDelay = entry. - entry.;
(appearanceDelay > thresholds.) {
violations.(
);
}
visibleDuration = entry. - entry.;
(visibleDuration < thresholds.) {
violations.(
);
}
(visibleDuration > thresholds.) {
violations.(
);
}
}
violations;
}
}
Best Practices
-
Always throttle the network when testing loading states. Without artificial latency, async operations complete too quickly for loading indicators to appear. Use Playwright's route interception to add realistic delays.
-
Test loading states on simulated slow 3G and offline modes. Mobile users on poor connections experience loading states for much longer. Verify the experience degrades gracefully.
-
Verify loading indicators appear within one animation frame. The delay between user action and visible feedback must be imperceptible. Enforce a threshold below 100ms.
-
Enforce a minimum display duration for loading indicators. A spinner that flashes for 50ms is worse than no spinner. Implement a minimum display time of 200ms to prevent visual flicker.
-
Test that skeleton screens match content layout. Capture bounding rectangles before and after content loads. Assert positions remain stable to prevent layout shift.
-
Verify loading states transition cleanly to error states. Failed requests must replace the loading indicator with an error message. A vanishing spinner with no content is a severe UX bug.
-
Test concurrent loading states independently. Multiple data-fetching sections should resolve their own loading states independently. One slow section should not block the entire page.
-
Record video of loading state tests. Loading bugs are temporal. Static screenshots miss the problem. Use Playwright's video recording to capture the full lifecycle.
-
Check aria-busy and aria-live attributes. Loading regions need aria-busy="true" during loading and an aria-live region must announce completion.
-
Test the stuck loading scenario. Simulate a request that never resolves. Verify the application shows a timeout message rather than spinning forever.
-
Measure Cumulative Layout Shift during loading transitions. Use the Performance Observer API to capture CLS values. CLS above 0.1 indicates poor skeleton implementation.
-
Test loading states across page navigations. SPA route-level loading indicators must appear during navigation and disappear when the new page renders.
Anti-Patterns to Avoid
-
No loading indicator at all. The most common anti-pattern. The user clicks a button and nothing visible happens for several seconds.
-
Spinner that never stops. A stuck loading state is worse than none. Always implement timeouts and fallback error messages.
-
Full-page loading overlay for partial updates. Blocking the entire page when only one section is refreshing is unnecessarily disruptive.
-
Skeleton screens that do not match content dimensions. Skeletons that differ from actual content cause layout shift, defeating their purpose.
-
Multiple concurrent spinners creating visual noise. Every card and widget having its own spinner looks chaotic. Use section-level indicators for grouped content.
-
Loading overlay that blocks user interaction unnecessarily. If the user can still use other parts of the page, do not block their input with a full-page overlay.
-
Flash of loading state on fast connections. A 30ms spinner creates visual flicker. Debounce the loading indicator or enforce a minimum display time.
-
Loading text without visual indicator. Plain "Loading..." text without animation looks like static content, not a transitional state.
-
Progress bar that jumps from 0% to 100%. If progress cannot be tracked incrementally, use an indeterminate indicator instead of a misleading progress bar.
-
Ignoring loading states in error recovery flows. A "Retry" button click must show loading again during the retry attempt.
Debugging Tips
-
Use Playwright's video recording for all loading transition tests. Videos capture temporal bugs that screenshots miss entirely.
-
Add artificial delays to API responses using page.route() to make loading states observable. A 3-5 second delay makes it easy to screenshot loading states.
-
Use Chrome DevTools Performance tab to identify layout shifts during loading transitions. The "Experience" row highlights CLS events.
-
Check the network waterfall to understand which requests are blocking resolution. Cascading sequential requests often cause unexpectedly long loading times.
-
Inspect CSS animations on loading indicators. Some spinners stop animating after a certain iteration count. Verify animations repeat indefinitely.
-
Test with CPU throttling enabled. Slow CPUs can cause rendering delays that make loading states appear jerky or incomplete.
-
Use MutationObserver to track DOM changes during loading transitions. This reveals race conditions where content and loading indicators briefly coexist.
-
Log timestamps for each state transition (idle, loading, success, error) to build a timeline. This helps identify gaps or overlaps between states.
-
Test with browser cache disabled. Cached responses skip the loading state entirely, masking missing implementations that only appear on first load.
-
Check for z-index conflicts between loading overlays and other elements. Loading overlays sometimes render behind modals or fixed headers due to stacking context issues.