nuxt-bdd-testing
Version:
Enhanced BDD testing utilities for Nuxt applications with vitest-cucumber integration
874 lines (865 loc) • 28 kB
text/typescript
/**
* @typedef {Object} QuickTestOptions
* @property {boolean} shallow - Use shallow mounting
* @property {Object} props - Props to pass to component
* @property {Object} slots - Slots to render
* @property {Object} global - Global config for mounting
* @property {boolean} autoProps - Auto-generate props from component
* @property {Array<string>} events - Events to test automatically
* @property {boolean} a11y - Run accessibility tests
* @property {Object} mocks - Framework composables to mock
* @property {number} timeout - Test timeout in ms
*/
/**
* One-liner component test with smart defaults and BDD-style expectations
* @param {string} name - Test suite name
* @param {Object} component - Vue component to test
* @param {QuickTestOptions} options - Test configuration options
* @returns {Object} Test suite with enhanced wrapper utilities
*/
declare function quickTest(name: string, component: any, options?: QuickTestOptions): any;
/**
* Batch test multiple components with same options
* @param {Array} components - Array of [name, component, options] tuples
* @returns {Array} Array of test results
*/
declare function batchTest(components: any[]): any[];
/**
* Test component with multiple prop combinations (prop matrix testing)
* @param {string} name - Test suite name
* @param {Object} component - Vue component
* @param {Array} propCombinations - Array of prop objects to test
* @returns {Object} Test suite with prop combinations
*/
declare function propMatrix(name: string, component: any, propCombinations: any[]): any;
type QuickTestOptions = {
/**
* - Use shallow mounting
*/
shallow: boolean;
/**
* - Props to pass to component
*/
props: any;
/**
* - Slots to render
*/
slots: any;
/**
* - Global config for mounting
*/
global: any;
/**
* - Auto-generate props from component
*/
autoProps: boolean;
/**
* - Events to test automatically
*/
events: Array<string>;
/**
* - Run accessibility tests
*/
a11y: boolean;
/**
* - Framework composables to mock
*/
mocks: any;
/**
* - Test timeout in ms
*/
timeout: number;
};
/**
* Enhanced mount function with automatic cleanup and BDD helpers
* @param {Object} component - Vue component to mount
* @param {Object} options - Mount options
* @returns {Promise<Object>} Enhanced wrapper with BDD helpers
*/
declare function mountWithExpectations(component: any, options?: any): Promise<any>;
/**
* Quick component test with minimal setup
* @param {Object} component - Vue component
* @param {Function} testFn - Test function receiving wrapper
* @param {Object} options - Mount options
*/
declare function quickMount(component: any, testFn: Function, options?: any): Promise<void>;
/**
* Test component with different props combinations
* @param {Object} component - Vue component
* @param {Array} propSets - Array of prop objects to test
* @param {Function} testFn - Test function for each prop set
*/
declare function testWithProps(component: any, propSets: any[], testFn: Function): Promise<void>;
/**
* Test component responsiveness across different viewport sizes
* @param {Object} component - Vue component
* @param {Array} viewports - Array of viewport size objects
* @param {Function} testFn - Test function for each viewport
*/
declare function testResponsive(component: any, viewports: any[], testFn: Function): Promise<void>;
/**
* Create a component test factory with common options
* @param {Object} defaultOptions - Default mount options
* @returns {Function} Factory function for mounting components
*/
declare function createMountFactory(defaultOptions?: any): Function;
/**
* Mock Nuxt composables for testing
* @param {Object} composables - Object with composable names and mock implementations
* @returns {Object} Mock object for global mocks
*/
declare function mockNuxtComposables(composables?: any): any;
/**
* Base factory class for generating test data
*/
declare class DataFactory {
constructor(defaultSeed?: number);
defaultSeed: number;
fixtures: Map<any, any>;
/**
* Set faker seed for consistent test data
* @param {number} seed - Seed value
*/
setSeed(seed?: number): void;
/**
* Reset faker seed to ensure consistency
*/
resetSeed(): void;
/**
* Generate data with overrides
* @param {Function} generator - Data generator function
* @param {Object} overrides - Properties to override
* @returns {*} Generated data with overrides applied
*/
generate(generator: Function, overrides?: any): any;
/**
* Generate multiple instances of data
* @param {Function} generator - Data generator function
* @param {number} count - Number of instances to generate
* @param {Object} overrides - Base overrides for all instances
* @returns {Array} Array of generated data objects
*/
generateMany(generator: Function, count?: number, overrides?: any): any[];
/**
* Store fixture data
* @param {string} name - Fixture name
* @param {*} data - Fixture data
*/
createFixture(name: string, data: any): void;
/**
* Load fixture data
* @param {string} name - Fixture name
* @returns {*} Fixture data
*/
getFixture(name: string): any;
/**
* Clear all fixtures
*/
clearFixtures(): void;
}
/**
* User data factory for generating user profiles
*/
declare class UserFactory extends DataFactory {
/**
* Generate base user data
* @param {Object} overrides - Properties to override
* @returns {Object} User data object
*/
static create(overrides?: any): any;
/**
* Create admin user
* @param {Object} overrides - Properties to override
* @returns {Object} Admin user data
*/
static createAdmin(overrides?: any): any;
/**
* Create new user (recently registered)
* @param {Object} overrides - Properties to override
* @returns {Object} New user data
*/
static createNew(overrides?: any): any;
/**
* Create bulk users
* @param {number} count - Number of users
* @param {Object} overrides - Base overrides
* @returns {Array} Array of user objects
*/
static createBulk(count?: number, overrides?: any): any[];
}
/**
* Content data factory for generating posts, articles, etc.
*/
declare class ContentFactory extends DataFactory {
/**
* Generate base content data
* @param {Object} overrides - Properties to override
* @returns {Object} Content data object
*/
static create(overrides?: any): any;
/**
* Create published article
* @param {Object} overrides - Properties to override
* @returns {Object} Published article data
*/
static createArticle(overrides?: any): any;
/**
* Create draft content
* @param {Object} overrides - Properties to override
* @returns {Object} Draft content data
*/
static createDraft(overrides?: any): any;
}
/**
* Form data factory for generating form inputs
*/
declare class FormFactory extends DataFactory {
/**
* Generate contact form data
* @param {Object} overrides - Properties to override
* @returns {Object} Contact form data
*/
static createContact(overrides?: any): any;
/**
* Generate registration form data
* @param {Object} overrides - Properties to override
* @returns {Object} Registration form data
*/
static createRegistration(overrides?: any): any;
/**
* Generate profile form data
* @param {Object} overrides - Properties to override
* @returns {Object} Profile form data
*/
static createProfile(overrides?: any): any;
}
/**
* API response factory for mocking API data
*/
declare class APIFactory extends DataFactory {
/**
* Generate paginated response
* @param {Array} data - Data array
* @param {Object} pagination - Pagination info
* @returns {Object} Paginated API response
*/
static createPaginated(data: any[], pagination?: any): any;
/**
* Generate error response
* @param {string} message - Error message
* @param {number} status - HTTP status code
* @returns {Object} Error API response
*/
static createError(message?: string, status?: number): any;
/**
* Generate success response
* @param {*} data - Response data
* @param {string} message - Success message
* @returns {Object} Success API response
*/
static createSuccess(data?: any, message?: string): any;
}
/**
* Global test data factory instance
*/
declare const testData: DataFactory;
/**
* Common test scenarios factory
*/
declare class ScenarioFactory {
/**
* Create authentication scenario data
* @returns {Object} Auth scenario data
*/
static createAuthScenario(): any;
/**
* Create CRUD scenario data
* @param {Function} factory - Data factory function
* @returns {Object} CRUD scenario data
*/
static createCRUDScenario(factory?: Function): any;
/**
* Create form validation scenario
* @returns {Object} Validation scenario data
*/
static createValidationScenario(): any;
}
/**
* Create a new isolated test context
* @returns {TestContext} New test context instance
*/
declare function createTestContext(): TestContext;
/**
* Create context-aware helpers
* @param {TestContext} context - Test context instance
* @returns {ContextHelpers} Context helpers
*/
declare function createContextHelpers(context?: TestContext): ContextHelpers;
/**
* Test context manager for sharing state across test utilities
*/
declare class TestContext {
/**
* Reset all context data
*/
reset(): void;
data: any;
mocks: Map<any, any> | undefined;
timers: Map<any, any> | undefined;
fixtures: Map<any, any> | undefined;
apiResponses: any[] | undefined;
formData: any;
user: any;
authToken: any;
lastApiResponse: any;
submittedFormData: any;
lastSubmittedForm: string | null | undefined;
/**
* Store arbitrary data
* @param {string} key - Data key
* @param {*} value - Data value
*/
set(key: string, value: any): void;
/**
* Retrieve stored data
* @param {string} key - Data key
* @param {*} defaultValue - Default value if key not found
* @returns {*} Stored value or default
*/
get(key: string, defaultValue?: any): any;
/**
* Check if data exists
* @param {string} key - Data key
* @returns {boolean} Whether key exists
*/
has(key: string): boolean;
/**
* Remove data
* @param {string} key - Data key
*/
delete(key: string): void;
/**
* Store mock function
* @param {string} name - Mock name
* @param {Function} mockFn - Mock function
*/
setMock(name: string, mockFn?: Function): Function;
/**
* Get mock function
* @param {string} name - Mock name
* @returns {Function} Mock function
*/
getMock(name: string): Function;
/**
* Clear all mocks
*/
clearMocks(): void;
/**
* Start a timer
* @param {string} name - Timer name
*/
startTimer(name: string): void;
/**
* Stop timer and get duration
* @param {string} name - Timer name
* @returns {number} Duration in ms
*/
stopTimer(name: string): number;
/**
* Store fixture data
* @param {string} name - Fixture name
* @param {*} data - Fixture data
*/
setFixture(name: string, data: any): void;
/**
* Get fixture data
* @param {string} name - Fixture name
* @returns {*} Fixture data
*/
getFixture(name: string): any;
/**
* Set authenticated user
* @param {Object} user - User object
* @param {string} token - Auth token
*/
setUser(user: any, token?: string): void;
/**
* Clear user authentication
*/
clearUser(): void;
/**
* Check if user is authenticated
* @returns {boolean} Authentication status
*/
isAuthenticated(): boolean;
/**
* Record API response
* @param {string} endpoint - API endpoint
* @param {*} response - API response
*/
recordApiResponse(endpoint: string, response: any): void;
/**
* Get last API response
* @returns {*} Last API response
*/
getLastApiResponse(): any;
/**
* Get all API responses
* @returns {Array} Array of API responses
*/
getApiResponses(): any[];
/**
* Store form data
* @param {Object} data - Form data
* @param {string} formSelector - Form selector
*/
setFormData(data: any, formSelector?: string): void;
/**
* Get form data
* @returns {Object} Current form data
*/
getFormData(): any;
/**
* Clear form data
*/
clearFormData(): void;
/**
* Create a scoped context for a test suite
* @param {string} scope - Scope name
* @returns {Object} Scoped context methods
*/
createScope(scope: string): any;
/**
* Export context data as JSON
* @returns {Object} Serializable context data
*/
export(): any;
/**
* Import context data from JSON
* @param {Object} contextData - Context data to import
*/
import(contextData: any): void;
}
/**
* Global test context instance
*/
declare const globalContext: TestContext;
/**
* Context-aware test helpers
*/
declare class ContextHelpers {
constructor(context?: TestContext);
context: TestContext;
/**
* Setup common test scenario
* @param {Object} options - Setup options
*/
setupScenario(options?: any): Promise<void>;
/**
* Cleanup context after test
*/
cleanup(): void;
/**
* Reset context completely
*/
reset(): void;
/**
* Assert context state
* @param {string} key - Data key to assert
* @param {*} expectedValue - Expected value
*/
assertState(key: string, expectedValue: any): void;
/**
* Wait for context condition
* @param {Function} condition - Condition function
* @param {number} timeout - Timeout in ms
* @returns {Promise<boolean>} Whether condition was met
*/
waitForCondition(condition: Function, timeout?: number): Promise<boolean>;
}
/**
* Create BDD-style expectation
* @param {*} subject - Subject to test
* @returns {BDDExpectations} BDD expectations wrapper
*/
declare function should(subject: any): BDDExpectations;
/**
* Accessibility assertion helpers
*/
declare class A11yAssertions {
/**
* Assert element has proper ARIA attributes
* @param {Element|Object} element - DOM element or wrapper
*/
static hasAriaLabels(element: Element | any): void;
/**
* Assert images have alt text
* @param {Element|Object} element - DOM element or wrapper
*/
static hasImageAltText(element: Element | any): void;
/**
* Assert proper heading hierarchy
* @param {Element|Object} element - DOM element or wrapper
*/
static hasProperHeadingHierarchy(element: Element | any): void;
/**
* Assert proper focus management
* @param {Element|Object} element - DOM element or wrapper
*/
static hasFocusManagement(element: Element | any): void;
}
/**
* Performance assertion helpers
*/
declare class PerformanceAssertions {
/**
* Assert operation completes within time limit
* @param {Function} operation - Operation to test
* @param {number} maxTime - Maximum time in ms
* @returns {Promise<number>} Actual execution time
*/
static completesWithin(operation: Function, maxTime: number): Promise<number>;
/**
* Assert memory usage doesn't exceed threshold
* @param {Function} operation - Operation to test
* @param {number} maxMemoryMB - Maximum memory in MB
*/
static memoryUsageWithin(operation: Function, maxMemoryMB: number): Promise<void>;
}
/**
* Component assertion helpers
*/
declare class ComponentAssertions {
/**
* Assert component renders without errors
* @param {Object} wrapper - Component wrapper
*/
static rendersWithoutErrors(wrapper: any): void;
/**
* Assert component contains text
* @param {Object} wrapper - Component wrapper
* @param {string} text - Text to find
*/
static containsText(wrapper: any, text: string): void;
/**
* Assert component has CSS class
* @param {Object} wrapper - Component wrapper
* @param {string} className - CSS class name
*/
static hasClass(wrapper: any, className: string): void;
/**
* Assert component emitted event
* @param {Object} wrapper - Component wrapper
* @param {string} eventName - Event name
* @param {*} expectedPayload - Expected event payload
*/
static emittedEvent(wrapper: any, eventName: string, expectedPayload?: any): void;
/**
* Assert component has attribute
* @param {Object} wrapper - Component wrapper
* @param {string} attribute - Attribute name
* @param {string} expectedValue - Expected attribute value
*/
static hasAttribute(wrapper: any, attribute: string, expectedValue?: string): void;
/**
* Assert component props are valid
* @param {Object} wrapper - Component wrapper
* @param {Object} component - Component definition
*/
static hasValidProps(wrapper: any, component: any): void;
}
/**
* API assertion helpers
*/
declare class APIAssertions {
/**
* Assert API response has correct structure
* @param {Object} response - API response
* @param {Object} expectedStructure - Expected response structure
*/
static hasStructure(response: any, expectedStructure: any): void;
/**
* Assert paginated response structure
* @param {Object} response - API response
*/
static isPaginated(response: any): void;
/**
* Assert error response structure
* @param {Object} response - API error response
* @param {number} expectedStatus - Expected status code
*/
static isError(response: any, expectedStatus?: number): void;
}
/**
* Form assertion helpers
*/
declare class FormAssertions {
/**
* Assert form field has validation error
* @param {Object} wrapper - Component wrapper
* @param {string} fieldName - Field name or selector
* @param {string} expectedError - Expected error message
*/
static hasValidationError(wrapper: any, fieldName: string, expectedError?: string): void;
/**
* Assert form is in loading state
* @param {Object} wrapper - Component wrapper
*/
static isLoading(wrapper: any): void;
/**
* Assert form fields are populated correctly
* @param {Object} wrapper - Component wrapper
* @param {Object} expectedData - Expected form data
*/
static hasFormData(wrapper: any, expectedData: any): void;
}
declare namespace customMatchers {
function toBeAccessible(received: any): {
pass: boolean;
message: () => string;
};
function toRenderWithoutErrors(received: any): {
pass: boolean;
message: () => string;
};
function toHaveValidProps(received: any, component: any): {
pass: boolean;
message: () => string;
};
}
/**
* BDD-style expectation wrapper
*/
declare class BDDExpectations {
constructor(subject: any);
subject: any;
/**
* Component should render
*/
toRender(): this;
/**
* Component should contain text
* @param {string} text - Text to find
*/
toContain(text: string): this;
/**
* Component should have CSS class
* @param {string} className - CSS class name
*/
toHaveClass(className: string): this;
/**
* Component should emit event
* @param {string} eventName - Event name
* @param {*} payload - Expected payload
*/
toEmit(eventName: string, payload: any): this;
/**
* Component should be accessible
*/
toBeAccessible(): this;
}
/**
* Quick performance test function
* @param {string} name - Test name
* @param {Function} operation - Operation to test
* @param {Object} options - Test options
* @returns {Promise<Object>} Performance metrics
*/
declare function perfTest(name: string, operation: Function, options?: any): Promise<any>;
/**
* Memory leak detection test
* @param {Function} operation - Operation to test
* @param {number} iterations - Number of iterations
* @param {number} maxIncreaseMB - Maximum memory increase in MB
* @returns {Promise<Object>} Memory metrics
*/
declare function memoryLeakTest(operation: Function, iterations?: number, maxIncreaseMB?: number): Promise<any>;
/**
* Component render performance test
* @param {string} componentName - Component name
* @param {Function} renderFn - Render function
* @param {Object} options - Test options
* @returns {Promise<Object>} Render metrics
*/
declare function renderPerfTest(componentName: string, renderFn: Function, options?: any): Promise<any>;
/**
* Performance measurement and assertion utilities
*/
declare class PerformanceTester {
measurements: Map<any, any>;
thresholds: {
renderTime: number;
paintTime: number;
layoutTime: number;
scriptTime: number;
interactionTime: number;
memoryMB: number;
};
/**
* Measure operation execution time
* @param {string} name - Measurement name
* @param {Function} operation - Operation to measure
* @param {Object} options - Measurement options
* @returns {Promise<Object>} Performance metrics
*/
measure(name: string, operation: Function, options?: any): Promise<any>;
/**
* Measure component render time
* @param {string} componentName - Component name
* @param {Function} renderFn - Render function
* @param {Object} options - Options
* @returns {Promise<Object>} Render metrics
*/
measureRender(componentName: string, renderFn: Function, options?: any): Promise<any>;
/**
* Measure user interaction response time
* @param {string} interactionName - Interaction name
* @param {Function} interactionFn - Interaction function
* @param {Object} options - Options
* @returns {Promise<Object>} Interaction metrics
*/
measureInteraction(interactionName: string, interactionFn: Function, options?: any): Promise<any>;
/**
* Measure memory usage during operation
* @param {Function} operation - Operation to measure
* @param {Object} options - Options
* @returns {Promise<Object>} Memory metrics
*/
measureMemory(operation: Function, options?: any): Promise<any>;
/**
* Assert operation meets performance threshold
* @param {string} name - Measurement name
* @param {number} threshold - Threshold in ms
* @param {string} message - Custom message
*/
expectWithinThreshold(name: string, threshold: number, message: string): void;
/**
* Assert consistent performance (low variance)
* @param {string} name - Measurement name
* @param {number} maxVariancePercent - Maximum variance percentage
*/
expectConsistent(name: string, maxVariancePercent?: number): void;
/**
* Assert memory usage within limit
* @param {Object} memoryMetrics - Memory metrics from measureMemory
* @param {number} maxIncreaseMB - Maximum memory increase in MB
*/
expectMemoryWithin(memoryMetrics: any, maxIncreaseMB?: number): void;
/**
* Create performance benchmark suite
* @param {Object} operations - Object with operation names and functions
* @param {Object} options - Benchmark options
* @returns {Promise<Object>} Benchmark results
*/
benchmark(operations: any, options?: any): Promise<any>;
/**
* Generate performance report
* @param {Object} results - Benchmark results
* @returns {string} Formatted report
*/
generateReport(results: any): string;
/**
* Measure Web Vitals (where available)
* @returns {Promise<Object>} Web Vitals metrics
*/
measureWebVitals(): Promise<any>;
/**
* Create performance test decorator
* @param {Object} options - Performance options
* @returns {Function} Decorator function
*/
withPerformanceTest(options?: any): Function;
/**
* Reset all measurements
*/
reset(): void;
/**
* Export measurements data
* @returns {Object} All measurements
*/
export(): any;
/**
* Calculate statistical metrics from measurements
* @private
* @param {Array} measurements - Array of measurement values
* @returns {Object} Statistical metrics
*/
private _calculateMetrics;
/**
* Get current memory usage
* @private
* @returns {number} Memory usage in bytes
*/
private _getMemoryUsage;
/**
* Get performance grade based on threshold
* @private
* @param {number} actual - Actual performance value
* @param {number} threshold - Threshold value
* @returns {string} Performance grade
*/
private _getPerformanceGrade;
/**
* Measure Largest Contentful Paint
* @private
* @returns {Promise<number>} LCP value
*/
private _measureLCP;
/**
* Measure Cumulative Layout Shift
* @private
* @returns {Promise<number>} CLS value
*/
private _measureCLS;
/**
* Measure First Input Delay
* @private
* @returns {Promise<number>} FID value
*/
private _measureFID;
}
/**
* Global performance tester instance
*/
declare const perf: PerformanceTester;
/**
* Create a complete testing environment with all utilities
* @param {Object} options - Configuration options
* @returns {Object} Complete testing environment
*/
declare function createTestingEnvironment(options?: any): any;
/**
* Default testing environment for quick setup
*/
declare const defaultEnvironment: any;
declare namespace scenarios {
function authenticatedUser(userOverrides?: any): any;
function crudOperations(factory?: Function): any;
function formValidation(): any;
}
declare namespace patterns {
function responsive(component: any, testFn: Function, viewports?: any[]): any;
function accessibility(component: any, options?: any): Promise<void>;
function performance(name: string, component: any, options?: any): Promise<any>;
}
/**
* Version information
*/
declare const version: "1.0.0";
declare namespace _default {
export let quickTest: any;
export let quickMount: any;
export let mountWithExpectations: any;
export let UserFactory: any;
export let ContentFactory: any;
export let FormFactory: any;
export let should: any;
export let perf: any;
export { scenarios };
export { patterns };
export { createTestingEnvironment };
export { defaultEnvironment };
export { version };
}
export { A11yAssertions, APIAssertions, APIFactory, BDDExpectations, ComponentAssertions, ContentFactory, ContextHelpers, DataFactory, FormAssertions, FormFactory, PerformanceAssertions, PerformanceTester, ScenarioFactory, TestContext, UserFactory, A11yAssertions as a11y, APIAssertions as api, batchTest, ComponentAssertions as component, createContextHelpers, createMountFactory, createTestContext, createTestingEnvironment, customMatchers, _default as default, defaultEnvironment, FormAssertions as form, globalContext, memoryLeakTest, mockNuxtComposables, mountWithExpectations, patterns, perf, perfTest, PerformanceAssertions as performance, propMatrix, quickMount, quickTest, renderPerfTest, scenarios, should, testData, testResponsive, testWithProps, version };