or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

app-component-creation.mdautomation.mdbuild-configuration.mdindex.mdnavigation-apis.mdnetwork-apis.mdruntime-api.mdsystem-apis.mdvue-integration.md
tile.json

automation.mddocs/

Automation and Testing

Built-in automation capabilities for testing and debugging Baidu Mini Program applications. This module provides DevTools integration, automated testing APIs, and runtime inspection capabilities for comprehensive application testing and debugging.

Capabilities

Runtime Automator Initialization

Core initialization function for setting up automation capabilities in the Baidu Mini Program runtime. This function is available on the global swan object when running in the Baidu Mini Program environment.

/**
 * Initialize automation runtime for testing and debugging
 * Available globally as swan.$$initRuntimeAutomator in Baidu Mini Program runtime
 * @param options - Optional automator configuration
 */
function $$initRuntimeAutomator(options?: AutomatorOptions): void;

interface AutomatorOptions {
  /** Enable DevTools integration */
  devtools?: boolean;
  /** Enable element selection */
  elementSelector?: boolean;
  /** Enable performance monitoring */
  performance?: boolean;
  /** Debug mode settings */
  debug?: {
    /** Log level */
    level?: 'error' | 'warn' | 'info' | 'debug';
    /** Enable API call logging */
    logAPICalls?: boolean;
    /** Enable event logging */
    logEvents?: boolean;
  };
  /** Custom automation extensions */
  extensions?: AutomatorExtension[];
}

interface AutomatorExtension {
  /** Extension name */
  name: string;
  /** Extension initialization */
  init?(automator: RuntimeAutomator): void;
  /** Extension methods */
  methods?: Record<string, Function>;
}

Usage Example:

// Available globally in Baidu Mini Program runtime environment
// No import needed - use swan global object

// Initialize automation for testing
swan.$$initRuntimeAutomator({
  devtools: true,
  elementSelector: true,
  performance: true,
  debug: {
    level: 'debug',
    logAPICalls: true,
    logEvents: true
  }
});

Page Automation APIs

Automation interfaces for page-level testing and inspection.

/**
 * Page automation API for testing page interactions
 */
interface PageAutomatorAPI {
  /**
   * Get current page data
   * @returns Page data object
   */
  getData(): PageData;
  
  /**
   * Set page data for testing
   * @param data - Data to set
   */
  setData(data: Partial<PageData>): void;
  
  /**
   * Call page method for testing
   * @param method - Method name to call
   * @param args - Arguments to pass to method
   * @returns Method return value
   */
  callMethod(method: string, args?: any[]): any;
  
  /**
   * Simulate page lifecycle events
   * @param event - Lifecycle event name
   * @param options - Event options
   */
  triggerLifecycle(event: PageLifecycleEvent, options?: any): void;
  
  /**
   * Get page element by selector
   * @param selector - Element selector
   * @returns Element automation interface
   */
  querySelector(selector: string): ElementAutomator | null;
  
  /**
   * Get multiple page elements by selector
   * @param selector - Element selector
   * @returns Array of element automation interfaces
   */
  querySelectorAll(selector: string): ElementAutomator[];
}

interface PageData {
  [key: string]: any;
}

type PageLifecycleEvent = 
  | 'onLoad' 
  | 'onShow' 
  | 'onReady' 
  | 'onHide' 
  | 'onUnload'
  | 'onPullDownRefresh'
  | 'onReachBottom';

Usage Example:

// In test environment
const page = getCurrentPage();
const automator = page.$$automator;

// Test page data
const data = automator.getData();
console.log('Current page data:', data);

// Simulate user interaction
automator.setData({ userInput: 'test value' });
automator.callMethod('handleSubmit');

// Test lifecycle events
automator.triggerLifecycle('onShow');

Component Automation APIs

Automation interfaces for component-level testing and inspection.

/**
 * Component automation API for testing component behavior
 */
interface ComponentAutomatorAPI {
  /**
   * Get component data
   * @returns Component data object
   */
  getData(): ComponentData;
  
  /**
   * Set component data for testing
   * @param data - Data to set
   */
  setData(data: Partial<ComponentData>): void;
  
  /**
   * Call component method
   * @param method - Method name to call
   * @param args - Arguments to pass to method
   * @returns Method return value
   */
  callMethod(method: string, args?: any[]): any;
  
  /**
   * Get component properties
   * @returns Component props
   */
  getProps(): ComponentProps;
  
  /**
   * Set component properties for testing
   * @param props - Props to set
   */
  setProps(props: Partial<ComponentProps>): void;
  
  /**
   * Trigger component events
   * @param event - Event name
   * @param detail - Event detail data
   */
  triggerEvent(event: string, detail?: any): void;
  
  /**
   * Simulate component lifecycle
   * @param event - Lifecycle event name
   */
  triggerLifecycle(event: ComponentLifecycleEvent): void;
}

interface ComponentData {
  [key: string]: any;
}

interface ComponentProps {
  [key: string]: any;
}

type ComponentLifecycleEvent = 
  | 'created' 
  | 'attached' 
  | 'ready' 
  | 'moved' 
  | 'detached';

Usage Example:

// Test component behavior
const component = selectComponent('#my-component');
const automator = component.$$automator;

// Test component props
automator.setProps({ title: 'Test Title', visible: true });
const props = automator.getProps();
console.log('Component props:', props);

// Test component methods
const result = automator.callMethod('calculate', [1, 2, 3]);
console.log('Method result:', result);

// Test component events
automator.triggerEvent('custom-event', { value: 'test' });

App Automation APIs

Application-level automation for testing app behavior and navigation.

/**
 * App automation API for testing application-level behavior
 */
interface AppAutomatorAPI {
  /**
   * Get current page stack
   * @returns Array of page instances
   */
  getPageStack(): PageInstance[];
  
  /**
   * Get current page instance
   * @returns Current page instance
   */
  getCurrentPage(): PageInstance | null;
  
  /**
   * Call uni-app method for testing
   * @param method - Method name (e.g., 'navigateTo', 'showToast')
   * @param args - Method arguments
   * @returns Promise resolving to method result
   */
  callUniMethod(method: string, args?: any): Promise<any>;
  
  /**
   * Mock uni-app method for testing
   * @param method - Method name to mock
   * @param mock - Mock implementation or return value
   */
  mockUniMethod(method: string, mock: Function | any): void;
  
  /**
   * Restore mocked methods
   * @param method - Optional specific method to restore
   */
  restoreMocks(method?: string): void;
  
  /**
   * Navigate to page for testing
   * @param path - Page path
   * @param query - Query parameters
   */
  navigateToPage(path: string, query?: Record<string, any>): Promise<void>;
  
  /**
   * Get app global data
   * @returns App global data
   */
  getGlobalData(): any;
  
  /**
   * Set app global data for testing
   * @param data - Global data to set
   */
  setGlobalData(data: any): void;
}

interface PageInstance {
  /** Page route */
  route: string;
  /** Page options */
  options: any;
  /** Page data */
  data: any;
  /** Page automation API */
  $$automator: PageAutomatorAPI;
}

Usage Example:

// Test app-level functionality
const app = getApp();
const automator = app.$$automator;

// Test navigation
await automator.navigateToPage('/pages/detail/detail', { id: '123' });

// Test page stack
const pageStack = automator.getPageStack();
console.log('Current page stack:', pageStack.map(p => p.route));

// Mock uni API for testing
automator.mockUniMethod('showToast', (options) => {
  console.log('Mock toast:', options.title);
  return Promise.resolve();
});

// Test mocked API
await automator.callUniMethod('showToast', { title: 'Test Toast' });

// Restore mocks
automator.restoreMocks();

Element Automation

Interface for automating interactions with page elements.

/**
 * Element automation interface for simulating user interactions
 */
interface ElementAutomator {
  /**
   * Get element properties
   * @returns Element properties
   */
  getProperties(): ElementProperties;
  
  /**
   * Get element computed style
   * @returns Computed style object
   */
  getComputedStyle(): ComputedStyle;
  
  /**
   * Simulate tap/click event
   * @param options - Tap options
   */
  tap(options?: TapOptions): void;
  
  /**
   * Simulate long press event
   * @param options - Long press options
   */
  longPress(options?: LongPressOptions): void;
  
  /**
   * Simulate input for input elements
   * @param value - Input value
   */
  input(value: string): void;
  
  /**
   * Simulate swipe gesture
   * @param direction - Swipe direction
   * @param distance - Swipe distance
   */
  swipe(direction: SwipeDirection, distance?: number): void;
  
  /**
   * Check if element is visible
   * @returns True if element is visible
   */
  isVisible(): boolean;
  
  /**
   * Get element bounding box
   * @returns Element position and size
   */
  getBoundingBox(): BoundingBox;
}

interface ElementProperties {
  /** Element ID */
  id?: string;
  /** Element class names */
  className?: string;
  /** Element dataset */
  dataset?: Record<string, any>;
  /** Element attributes */
  attributes?: Record<string, string>;
  /** Element text content */
  textContent?: string;
}

interface ComputedStyle {
  /** Element dimensions */
  width: number;
  height: number;
  /** Element position */
  left: number;
  top: number;
  /** Element styling */
  color?: string;
  backgroundColor?: string;
  fontSize?: string;
  [key: string]: any;
}

interface TapOptions {
  /** Tap position offset */
  x?: number;
  y?: number;
  /** Tap duration */
  duration?: number;
}

interface LongPressOptions extends TapOptions {
  /** Long press duration */
  duration: number;
}

type SwipeDirection = 'up' | 'down' | 'left' | 'right';

interface BoundingBox {
  /** Left position */
  left: number;
  /** Top position */
  top: number;
  /** Width */
  width: number;
  /** Height */
  height: number;
  /** Right position */
  right: number;
  /** Bottom position */
  bottom: number;
}

DevTools Integration

Integration with Baidu DevTools for debugging and inspection.

/**
 * DevTools integration for debugging and development
 */
interface DevToolsIntegration {
  /**
   * Connect to DevTools
   * @param options - Connection options
   */
  connect(options?: DevToolsOptions): Promise<void>;
  
  /**
   * Disconnect from DevTools
   */
  disconnect(): void;
  
  /**
   * Send message to DevTools
   * @param message - Message to send
   */
  sendMessage(message: DevToolsMessage): void;
  
  /**
   * Listen for DevTools messages
   * @param listener - Message listener
   */
  onMessage(listener: (message: DevToolsMessage) => void): void;
  
  /**
   * Inspect element in DevTools
   * @param element - Element to inspect
   */
  inspectElement(element: any): void;
  
  /**
   * Log to DevTools console
   * @param level - Log level
   * @param args - Log arguments
   */
  console(level: 'log' | 'warn' | 'error' | 'info', ...args: any[]): void;
}

interface DevToolsOptions {
  /** DevTools host */
  host?: string;
  /** DevTools port */
  port?: number;
  /** Auto-connect */
  autoConnect?: boolean;
}

interface DevToolsMessage {
  /** Message type */
  type: string;
  /** Message payload */
  payload: any;
  /** Message ID */
  id?: string;
}

Testing Examples

Unit Testing with Automation

// Example unit test using automation APIs
describe('UserProfile Component', () => {
  let component;
  
  beforeEach(() => {
    // Initialize component with automation
    component = createComponent({
      data: () => ({ name: '', email: '' }),
      methods: {
        updateProfile() {
          // Component logic
        }
      }
    });
    
    swan.$$initRuntimeAutomator({ debug: { level: 'debug' } });
  });
  
  it('should update user profile', () => {
    const automator = component.$$automator;
    
    // Set test data
    automator.setData({ name: 'John Doe', email: 'john@example.com' });
    
    // Call method
    const result = automator.callMethod('updateProfile');
    
    // Verify result
    expect(result).toBeTruthy();
    
    // Check data state
    const data = automator.getData();
    expect(data.name).toBe('John Doe');
  });
});

Integration Testing

// Example integration test
describe('Shopping Cart Flow', () => {
  let app;
  
  beforeEach(async () => {
    app = getApp();
    swan.$$initRuntimeAutomator({ 
      devtools: true,
      performance: true 
    });
  });
  
  it('should complete purchase flow', async () => {
    const automator = app.$$automator;
    
    // Navigate to product page
    await automator.navigateToPage('/pages/product/product', { id: '123' });
    
    // Add to cart
    const page = automator.getCurrentPage();
    const addButton = page.$$automator.querySelector('#add-to-cart');
    addButton.tap();
    
    // Navigate to cart
    await automator.navigateToPage('/pages/cart/cart');
    
    // Verify cart contents
    const cartPage = automator.getCurrentPage();
    const cartData = cartPage.$$automator.getData();
    expect(cartData.items).toHaveLength(1);
  });
});

Performance Testing

// Example performance testing
describe('Performance Tests', () => {
  it('should render page within acceptable time', async () => {
    swan.$$initRuntimeAutomator({ 
      performance: true,
      debug: { logAPICalls: true }
    });
    
    const startTime = performance.now();
    
    // Navigate to heavy page
    await app.$$automator.navigateToPage('/pages/dashboard/dashboard');
    
    const endTime = performance.now();
    const renderTime = endTime - startTime;
    
    // Assert performance requirement
    expect(renderTime).toBeLessThan(1000); // 1 second
  });
});