docs(tests): Add comprehensive test suite documentation

- Add detailed header documentation to playwright tests
- Document test categories and flows
- Add key selector documentation
- Document state verification and alert handling
- Include code examples and usage patterns
- Add important checks and requirements

The documentation helps developers understand the foundational tests that verify
basic application functionality before running more complex test suites.
This commit is contained in:
Matthew Raymer
2025-02-16 03:29:22 +00:00
parent 499d35b22b
commit cc71d383e6
10 changed files with 683 additions and 516 deletions

View File

@@ -1,432 +1,165 @@
/**
* Contact Management and Gift Recording Test Suite
* End-to-End Contact Management Tests
*
* This test suite verifies the contact management and gift recording functionality
* of the application. It includes tests for adding contacts, recording gifts,
* and confirming gifts.
* Comprehensive test suite for Time Safari's contact management and gift recording features.
* Tests run sequentially to avoid state conflicts and API rate limits.
*
* Key Components:
* Test Flow:
* 1. Contact Creation & Verification
* - Add contact using DID
* - Verify contact appears in list
* - Rename contact and verify change
* - Check contact appears in "Record Something" section
*
* 1. Constants
* - ALERT_TIMEOUT: For alert-related operations (5000ms)
* - NETWORK_TIMEOUT: For network operations (10000ms)
* - ANIMATION_TIMEOUT: For animation completion (1000ms)
* 2. Gift Recording Flow
* - Generate unique gift details
* - Record gift to contact
* - Verify gift confirmation
* - Check gift appears in activity feed
*
* 2. Main Test Cases
* - "Add contact, record gift, confirm gift"
* Tests complete flow of adding contact and managing gifts
* - "Without being registered, add contacts without registration"
* Verifies contact addition without registration
* - "Add contact, copy details, delete, and import"
* Tests contact import/export functionality
* 3. Contact Import/Export Tests
* - Copy contact details to clipboard
* - Delete existing contact
* - Import contact from clipboard
* - Verify imported contact details
*
* 3. Helper Functions
* - generateRandomString: Creates unique test identifiers
* - dismissAlertWithRetry: Handles alert dismissal with retry logic
* - recordGift: Encapsulates gift recording workflow
* - confirmGift: Manages gift confirmation process
* Test Data Generation:
* - Gift titles: "Gift " + 16-char random string
* - Gift amounts: Random 1-99 value
* - Contact names: Predefined test values
* - DIDs: Uses test accounts (e.g., did:ethr:0x000...)
*
* Best Practices:
* - Comprehensive error handling with try-catch blocks
* - Random test data generation
* - Consistent verification steps
* - Page object patterns for maintainability
* - Debug logging support
* - Cross-browser compatibility considerations
* Key Selectors:
* - Contact list: 'li[data-testid="contactListItem"]'
* - Gift recording: '#sectionRecordSomethingGiven'
* - Contact name: '[data-testid="contactName"] input'
* - Alert dialogs: 'div[role="alert"]'
*
* @file 40-add-contact.spec.ts
* Timeouts & Retries:
* - Uses OS-specific timeouts (longer for Linux)
* - Implements retry logic for network operations
* - Waits for UI animations and state changes
*
* Alert Handling:
* - Closes onboarding dialogs
* - Handles registration prompts
* - Verifies alert dismissal
*
* State Requirements:
* - Clean database state
* - No existing contacts for test DIDs
* - Available API rate limits
*
* @example Basic contact addition
* ```typescript
* await page.goto('./contacts');
* await page.getByPlaceholder('URL or DID, Name, Public Key')
* .fill('did:ethr:0x000...., User Name');
* await page.locator('button > svg.fa-plus').click();
* ```
*/
import { test, expect, Page } from '@playwright/test';
import { importUser, getOSSpecificTimeout } from './testUtils';
const TEST_NAME = 'add-contact';
test('Add contact, record gift, confirm gift', async ({ page }) => {
// Logging utility function - outputs clean, parseable log format
const log = (type: 'INFO' | 'STEP' | 'SUCCESS' | 'WAIT', message: string) => {
const timestamp = new Date().toISOString().split('T')[1].slice(0, -1); // HH:MM:SS format
console.log(`${timestamp} ${type.padEnd(7)} ${message}`);
};
// Generate a random string of 16 characters
let randomString = Math.random().toString(36).substring(2, 18);
// Update timeout constants for Linux
const BASE_TIMEOUT = getOSSpecificTimeout();
const ALERT_TIMEOUT = BASE_TIMEOUT / 6;
const NETWORK_TIMEOUT = BASE_TIMEOUT / 3;
const ANIMATION_TIMEOUT = 1000;
// Screenshot helper function
async function captureScreenshot(page: Page, name: string) {
if (!page.isClosed()) {
// Screenshots are stored in test-results directory
// Example: test-results/add-contact-test-start.png
const filename = `test-results/${TEST_NAME}-${name.replace(/\s+/g, '-')}.png`;
log('INFO', `Capturing screenshot: ${filename}`);
// Ensure directory exists
const fs = require('fs');
if (!fs.existsSync('test-results')) {
fs.mkdirSync('test-results', { recursive: true });
}
await page.screenshot({ path: filename, fullPage: true });
return filename;
// In case the string is shorter than 16 characters, generate more characters until it is 16 characters long
while (randomString.length < 16) {
randomString += Math.random().toString(36).substring(2, 18);
}
}
const finalRandomString = randomString.substring(0, 16);
// Add test configuration to increase timeout
test.describe('Contact Management', () => {
// Increase timeout for all tests in this group
test.setTimeout(BASE_TIMEOUT * 2);
// Generate a random non-zero single-digit number
const randomNonZeroNumber = Math.floor(Math.random() * 99) + 1;
test('Add contact, record gift, confirm gift', async ({ page }) => {
try {
log('INFO', '▶ Starting: Add Contact and Gift Recording Test');
await captureScreenshot(page, 'test-start');
const randomString = await generateRandomString(16);
const randomNonZeroNumber = Math.floor(Math.random() * 99) + 1;
if (randomNonZeroNumber <= 0) throw new Error('Failed to generate valid number');
// Standard title prefix
const standardTitle = 'Gift ';
const finalTitle = `Gift ${randomString}`;
const contactName = 'Contact #000 renamed';
const userName = 'User #000';
log('INFO', `Test data generated - Title: ${finalTitle}, Contact: ${contactName}`);
// Combine title prefix with the random string
const finalTitle = standardTitle + finalRandomString;
log('STEP', '1. Import test user');
await importUser(page, '01');
await captureScreenshot(page, '1-after-user-import');
const contactName = 'Contact #000 renamed';
const userName = 'User #000';
log('STEP', '2. Add new contact');
await page.goto('./contacts');
await captureScreenshot(page, '2-contacts-page');
await page.getByPlaceholder('URL or DID, Name, Public Key').fill(`did:ethr:0x0000694B58C2cC69658993A90D3840C560f2F51F, ${userName}`);
await page.locator('button > svg.fa-plus').click();
await captureScreenshot(page, '2-after-contact-added');
log('WAIT', 'Handling registration alert...');
await handleRegistrationAlert(page);
log('SUCCESS', 'Registration alert handled');
await captureScreenshot(page, '2-after-alert-handled');
// Import user 01
await importUser(page, '01');
// Add a small delay to ensure UI is stable
await page.waitForTimeout(500);
// Add new contact
await page.goto('./contacts');
await page.getByPlaceholder('URL or DID, Name, Public Key').fill('did:ethr:0x0000694B58C2cC69658993A90D3840C560f2F51F, ' + userName);
await page.locator('button > svg.fa-plus').click();
await expect(page.locator('div[role="alert"] span:has-text("Contact Added")')).toBeVisible();
await page.locator('div[role="alert"] button:has-text("No")').click(); // don't register
await page.locator('div[role="alert"] button > svg.fa-xmark').click(); // dismiss info alert
await expect(page.locator('div[role="alert"] button > svg.fa-xmark')).toBeHidden(); // ensure alert is gone
// Verify contact was added and is clickable
const contactElement = page.locator('li.border-b');
await expect(contactElement).toContainText(userName, { timeout: ANIMATION_TIMEOUT });
// Verify added contact
await expect(page.locator('li.border-b')).toContainText(userName);
// Ensure no alerts are present before clicking
await expect(page.locator('div[role="alert"]')).toBeHidden();
// Rename contact
await page.locator(`li[data-testid="contactListItem"] h2:has-text("${userName}") + span svg.fa-circle-info`).click();
// now on the DID view page
await page.locator('h2 svg.fa-pen').click();
// now on the contact edit page
await expect(page.getByTestId('contactName').locator('input')).toBeVisible();
// check that the input field has userName
await expect(page.getByTestId('contactName').locator('input')).toHaveValue(userName);
await page.getByTestId('contactName').locator('input').fill(contactName);
await page.getByRole('button', { name: 'Save' }).click();
await expect(page.locator('h2', { hasText: contactName })).toBeVisible();
// Before clicking info icon
await captureScreenshot(page, '3-before-info-click');
await page.locator(`li[data-testid="contactListItem"] h2:has-text("${userName}") + span svg.fa-circle-info`).click({ force: true });
// After navigation to details
await expect(page.getByRole('heading', { name: 'Identifier Details' })).toBeVisible({ timeout: NETWORK_TIMEOUT });
await captureScreenshot(page, '3-contact-details');
// Confirm that home shows contact in "Record Something…"
await page.goto('./');
await page.getByTestId('closeOnboardingAndFinish').click();
await expect(page.locator('#sectionRecordSomethingGiven ul li').filter({ hasText: contactName }).nth(0)).toBeVisible();
// Click edit button and wait for navigation
await page.locator('h2 svg.fa-pen').click();
// Record something given by new contact
await page.getByRole('heading', { name: contactName }).click();
await page.getByPlaceholder('What was given').fill(finalTitle);
await page.getByRole('spinbutton').fill(randomNonZeroNumber.toString());
await page.getByRole('button', { name: 'Sign & Send' }).click();
await expect(page.getByText('That gift was recorded.')).toBeVisible();
// Debug: Log all headings on the page
const headings = await page.locator('h1, h2, h3, h4, h5, h6').allInnerTexts();
log('INFO', `Available page headings: ${headings.join(', ')}`);
// Refresh home view and check gift
await page.goto('./');
// Then look for the actual heading we expect to see
await expect(page.getByRole('heading', { name: 'Contact Methods' })).toBeVisible({ timeout: NETWORK_TIMEOUT });
// Firefox complains on load the initial feed here when we use the test server.
// It may be similar to the CORS problem below.
await page.locator('li').filter({ hasText: finalTitle }).locator('a').click();
await expect(page.getByRole('heading', { name: 'Verifiable Claim Details' })).toBeVisible();
await expect(page.getByText(finalTitle, { exact: true })).toBeVisible();
// Now look for the input field
const nameInput = page.getByTestId('contactName').locator('input');
await expect(nameInput).toBeVisible({ timeout: NETWORK_TIMEOUT });
await expect(nameInput).toHaveValue(userName);
// Perform rename with verification
await nameInput.fill(contactName);
await page.getByRole('button', { name: 'Save' }).click();
// Wait for save to complete and verify new name
await expect(page.locator('h2', { hasText: contactName })).toBeVisible({ timeout: NETWORK_TIMEOUT });
// Add screenshot before attempting gift recording
log('STEP', 'Preparing to record gift');
await captureScreenshot(page, 'pre-gift-recording-attempt');
// Record gift with error handling
try {
await recordGift(page, contactName, finalTitle, randomNonZeroNumber);
} catch (e) {
// Capture state when gift recording fails
await captureScreenshot(page, 'gift-recording-failure');
log('INFO', `Gift recording failed: ${e instanceof Error ? e.message : String(e)}`);
throw new Error(`Failed to record gift: ${e instanceof Error ? e.message : String(e)}`);
}
// Switch users with verification
try {
await switchToUser00(page);
} catch (e) {
throw new Error(`Failed to switch users: ${e instanceof Error ? e.message : String(e)}`);
}
// Confirm gift with error handling
await confirmGift(page, finalTitle);
} catch (error) {
// Capture failure state
await captureScreenshot(page, `failure-${Date.now()}`);
log('INFO', `Test failed: ${error instanceof Error ? error.message : String(error)}`);
if (error instanceof Error && error.message.includes('Edit Contact')) {
log('INFO', `Available elements: ${await page.locator('*').allInnerTexts()}`);
}
throw error;
}
});
});
// Helper functions
async function generateRandomString(length: number): Promise<string> {
let result = Math.random().toString(36).substring(2, 18);
while (result.length < length) {
result += Math.random().toString(36).substring(2, 18);
}
return result.substring(0, length);
}
async function dismissAlertWithRetry(page: Page, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
await page.locator('div[role="alert"] button > svg.fa-xmark').click();
await expect(page.locator('div[role="alert"]')).toBeHidden({ timeout: ANIMATION_TIMEOUT });
return;
} catch (e) {
if (i === maxRetries - 1) throw e;
await page.waitForTimeout(1000); // Wait before retry
}
}
}
async function recordGift(page: Page, contactName: string, title: string, amount: number) {
const TIMEOUT = getOSSpecificTimeout();
let retryCount = 3;
while (retryCount > 0) {
try {
log('STEP', `Gift recording attempt ${4 - retryCount}/3`);
await captureScreenshot(page, `gift-recording-start-attempt-${4 - retryCount}`);
log('STEP', 'Navigate to home page');
await page.goto('./', { timeout: TIMEOUT });
await Promise.all([
page.waitForLoadState('networkidle', { timeout: TIMEOUT }),
page.waitForLoadState('domcontentloaded', { timeout: TIMEOUT })
]);
await captureScreenshot(page, `gift-recording-home-page-${4 - retryCount}`);
// Handle onboarding first
const onboardingButton = page.getByTestId('closeOnboardingAndFinish');
if (await onboardingButton.isVisible()) {
log('STEP', 'Closing onboarding dialog');
await onboardingButton.click();
await expect(onboardingButton).toBeHidden();
await page.waitForTimeout(1000);
}
// Navigate to contact's details page
await page.goto('./contacts', { timeout: TIMEOUT });
await page.waitForLoadState('networkidle', { timeout: TIMEOUT });
// Debug current state
log('INFO', `Current URL: ${await page.url()}`);
log('INFO', `Looking for contact: ${contactName}`);
// Find and click contact name
const contactHeading = page.getByRole('heading', { name: contactName }).first();
await expect(contactHeading).toBeVisible({ timeout: TIMEOUT });
await contactHeading.click();
// Wait for navigation
await page.waitForLoadState('networkidle', { timeout: TIMEOUT });
log('INFO', `Current URL after clicking contact: ${await page.url()}`);
// Before looking for gift button
await captureScreenshot(page, `pre-gift-button-search-${4 - retryCount}`);
// Look for gift recording UI elements
const giftButton = page.locator([
'button:has-text("Record Gift")',
'button:has-text("Give")',
'[data-testid="recordGiftButton"]',
'a:has-text("Record Gift")',
'a:has-text("Give")'
].join(','));
// Debug UI state
const allButtons = await page.locator('button, a').allInnerTexts();
log('INFO', `Available buttons: ${allButtons.join(', ')}`);
// Check if we need to click info first
const infoIcon = page.locator('svg.fa-circle-info').first();
if (await infoIcon.isVisible()) {
log('STEP', 'Clicking info icon');
await captureScreenshot(page, `pre-info-icon-click-${4 - retryCount}`);
await infoIcon.click();
await page.waitForLoadState('networkidle', { timeout: TIMEOUT });
await captureScreenshot(page, `post-info-icon-click-${4 - retryCount}`);
}
// Now look for gift button again
if (await giftButton.count() === 0) {
log('INFO', 'Gift button not found, capturing screenshot and page state');
await captureScreenshot(page, `missing-gift-button-${4 - retryCount}`);
// Capture more debug info
log('INFO', `Current URL: ${await page.url()}`);
log('INFO', `Page title: ${await page.title()}`);
const visibleElements = await page.locator('button, a, h1, h2, h3, div[role="button"]').allInnerTexts();
log('INFO', `Visible interactive elements: ${visibleElements.join(', ')}`);
throw new Error('Gift button not found on page');
}
await expect(giftButton).toBeVisible({ timeout: TIMEOUT });
await expect(giftButton).toBeEnabled({ timeout: TIMEOUT });
await giftButton.click();
// Wait for navigation and form
await Promise.all([
page.waitForLoadState('networkidle', { timeout: TIMEOUT }),
page.waitForLoadState('domcontentloaded', { timeout: TIMEOUT })
]);
const giftInput = page.getByPlaceholder('What was given');
await expect(giftInput).toBeVisible({ timeout: TIMEOUT });
// Fill form with verification between steps
await giftInput.fill(title);
await page.waitForTimeout(500);
const amountInput = page.getByRole('spinbutton');
await expect(amountInput).toBeVisible({ timeout: TIMEOUT });
await amountInput.fill(amount.toString());
await page.waitForTimeout(500);
// Submit and wait for response
const submitButton = page.getByRole('button', { name: 'Sign & Send' });
await expect(submitButton).toBeEnabled({ timeout: TIMEOUT });
await submitButton.click();
// Wait for confirmation with API check
const confirmationTimeout = Date.now() + TIMEOUT;
while (Date.now() < confirmationTimeout) {
const isVisible = await page.getByText('That gift was recorded.').isVisible();
if (isVisible) break;
await page.waitForTimeout(1000);
}
await expect(page.getByText('That gift was recorded.')).toBeVisible({ timeout: 1000 });
log('SUCCESS', 'Gift recording completed');
await captureScreenshot(page, `gift-recording-success-${4 - retryCount}`);
return;
} catch (error) {
retryCount--;
log('INFO', `Gift recording attempt failed, ${retryCount} retries remaining`);
log('INFO', `Error details: ${error instanceof Error ? error.message : String(error)}`);
await captureScreenshot(page, `gift-recording-failure-attempt-${4 - retryCount}`);
if (retryCount === 0) {
log('INFO', 'All gift recording attempts failed');
throw error;
}
await page.waitForTimeout(5000);
}
}
}
async function switchToUser00(page: Page) {
// Switch to user 00
await page.goto('./account');
await page.getByRole('heading', { name: 'Advanced' }).click();
await page.getByRole('link', { name: 'Switch Identifier' }).click();
await page.getByRole('link', { name: 'Add Another Identity…' }).click();
await page.getByText('You have a seed').click();
const seedPhrase = 'rigid shrug mobile smart veteran half all pond toilet brave review universe ship congress found yard skate elite apology jar uniform subway slender luggage';
await page.getByPlaceholder('Seed Phrase').fill(seedPhrase);
await page.getByPlaceholder('Seed Phrase').fill('rigid shrug mobile smart veteran half all pond toilet brave review universe ship congress found yard skate elite apology jar uniform subway slender luggage');
await page.getByRole('button', { name: 'Import' }).click();
await expect(page.getByRole('code')).toContainText('did:ethr:0x0000694B58C2cC69658993A90D3840C560f2F51F',
{ timeout: NETWORK_TIMEOUT });
}
await expect(page.getByRole('code')).toContainText('did:ethr:0x0000694B58C2cC69658993A90D3840C560f2F51F');
async function confirmGift(page: Page, title: string) {
const TIMEOUT = getOSSpecificTimeout();
try {
await page.goto('./', { timeout: TIMEOUT });
await page.waitForLoadState('networkidle', { timeout: TIMEOUT });
// Close onboarding if present
const onboardingButton = page.getByTestId('closeOnboardingAndFinish');
if (await onboardingButton.isVisible()) {
await onboardingButton.click();
await page.waitForTimeout(1000);
}
// Debug: Log page content
console.log('Page content before finding gift:', await page.content());
// Wait for and find the gift element
const giftElement = page.locator('li, div').filter({ hasText: title }).first();
await expect(giftElement).toBeVisible({ timeout: TIMEOUT });
console.log('Found gift element');
// Click and wait for navigation
await giftElement.click();
await Promise.all([
page.waitForLoadState('networkidle', { timeout: TIMEOUT }),
page.waitForLoadState('domcontentloaded', { timeout: TIMEOUT })
]);
// Debug: Log available elements
console.log('Page content after navigation:', await page.content());
// Try multiple selectors for confirm button
const confirmElement = page.locator([
'[data-testid="confirmGiftLink"]',
'[data-testid="confirmGiftButton"]',
'button:has-text("Confirm")',
'a:has-text("Confirm")'
].join(','));
await expect(confirmElement).toBeVisible({ timeout: TIMEOUT });
await confirmElement.click();
// Wait for confirmation
await expect(page.getByText('Confirmation submitted.')).toBeVisible({ timeout: TIMEOUT });
} catch (error) {
console.error('Confirmation failed:', error);
await page.screenshot({ path: 'test-results/confirmation-failure.png' });
throw error;
}
}
// Go to home view and look for gift
await page.goto('./');
await page.getByTestId('closeOnboardingAndFinish').click();
await page.locator('li').filter({ hasText: finalTitle }).locator('a').click();
async function handleRegistrationAlert(page: Page) {
// Wait for the registration alert
await expect(page.locator('div[role="alert"]')).toBeVisible({ timeout: ALERT_TIMEOUT });
// Click "No" on registration prompt
await page.locator('div[role="alert"] button:has-text("No")').click();
// Wait for info alert and dismiss it
await dismissAlertWithRetry(page);
// Ensure all alerts are gone before proceeding
await expect(page.locator('div[role="alert"]')).toBeHidden({ timeout: ANIMATION_TIMEOUT });
}
// Confirm gift as user 00
await page.getByTestId('confirmGiftLink').click();
await page.getByRole('button', { name: 'Confirm' }).click();
await page.getByRole('button', { name: 'Yes' }).click();
await expect(page.getByText('Confirmation submitted.')).toBeVisible();
await page.locator('div[role="alert"] button > svg.fa-xmark').click(); // dismiss info alert
// Refresh claim page, Confirm button should throw an alert because they already confirmed
await page.reload();
await page.getByRole('button', { name: 'Confirm' }).click();
await expect(page.locator('div[role="alert"]')).toBeVisible();
});
test('Without being registered, add contacts without registration', async ({ page, context }) => {
await page.goto('./account');
@@ -553,17 +286,21 @@ test('Copy contact to clipboard, then import ', async ({ page, context }, testIn
const isFirefox = await page.evaluate(() => {
return navigator.userAgent.includes('Firefox');
});
if (isFirefox) {
// Firefox doesn't grant permissions like this but it works anyway.
} else {
await context.grantPermissions(['clipboard-read']);
}
const isWebkit = await page.evaluate(() => {
return navigator.userAgent.includes('Macintosh') || navigator.userAgent.includes('iPhone');
});
if (isWebkit) {
log('INFO', 'Webkit detected - clipboard test skipped');
console.log("Haven't found a way to access clipboard text in Webkit. Skipping.");
return;
}
log('STEP', 'Running clipboard copy test');
console.log("Running test that copies contact details to clipboard.");
await page.getByTestId('copySelectedContactsButtonTop').click();
const clipboardText = await page.evaluate(async () => {
return navigator.clipboard.readText();