or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-karma-viewport

A Karma plugin for testing responsive features and layout

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/karma-viewport@1.0.x

To install, run

npx @tessl/cli install tessl/npm-karma-viewport@1.0.0

index.mddocs/

karma-viewport

karma-viewport is a Karma plugin for testing responsive features and layout. It provides a global viewport object that allows tests to dynamically resize iframe dimensions, configure named breakpoints for different screen sizes, and iterate through multiple viewport configurations during test execution.

Package Information

  • Package Name: karma-viewport
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install karma-viewport

Core Imports

karma-viewport is a Karma plugin, so it doesn't use traditional imports for the main functionality. Instead, you configure it in your Karma configuration file and access the global viewport object in your tests.

For advanced usage, you can import utility functions:

import { range, Viewport, ViewportConfiguration } from "karma-viewport";

Karma Configuration

// karma.conf.js
module.exports = function(config) {
  config.set({
    frameworks: ["viewport"],
    
    // Optional viewport configuration
    viewport: {
      context: "#context",  // iframe selector (default)
      breakpoints: [
        {
          name: "mobile",
          size: { width: 320, height: 480 }
        },
        {
          name: "tablet", 
          size: { width: 768, height: 1024 }
        },
        {
          name: "desktop",
          size: { width: 1440, height: 900 }
        }
      ]
    }
  });
};

TypeScript Support

/// <reference types="karma-viewport" />

Basic Usage

// Test file - viewport is available globally
describe("responsive layout", () => {
  
  beforeEach(() => {
    viewport.reset(); // Reset to default size
  });
  
  it("should work on mobile", () => {
    viewport.set(320, 480); // Set specific dimensions
    // Test mobile layout...
  });
  
  it("should work on tablet", () => {
    viewport.set("tablet"); // Use named breakpoint
    // Test tablet layout...
  });
  
  it("should test all breakpoints", () => {
    viewport.each(name => {
      // This runs for each configured breakpoint
      console.log(`Testing ${name} viewport`);
      // Test layout for current viewport...
    });
  });
});

Capabilities

Viewport Resizing

Core functionality for setting viewport dimensions using either pixel values or named breakpoints.

/**
 * Set viewport to specific width and optional height
 * @param width - Width in pixels
 * @param height - Optional height in pixels
 */
set(width: number, height?: number): void;

/**
 * Set viewport to named breakpoint
 * @param breakpoint - Name of configured breakpoint
 */
set(breakpoint: string): void;

/**
 * Reset viewport to default size (100% x 100%)
 */
reset(): void;

Document Loading

Load external HTML documents into the viewport iframe for testing complete pages.

/**
 * Load and embed document into viewport
 * @param url - URL of document to load  
 * @param cb - Optional callback function called after load completes
 * @returns Promise resolving with no result when load completes
 */
load(url: string, cb?: () => void): Promise<void>;

Scroll Control

Control the scroll position within the viewport iframe.

/**
 * Change viewport scroll offset
 * @param x - Horizontal offset in pixels
 * @param y - Vertical offset in pixels (default: 0)
 */
offset(x: number, y?: number): void;

Breakpoint Iteration

Execute test code across multiple viewport sizes using configured breakpoints.

/**
 * Execute callback for all configured breakpoints
 * @param cb - Callback function receiving breakpoint name
 * @returns Promise if callback returns Promise, void otherwise
 */
each<T>(cb: ViewportCallback<T>): void | Promise<void>;

/**
 * Execute callback for breakpoints starting from specified breakpoint
 * @param first - First breakpoint name
 * @param cb - Callback function receiving breakpoint name
 * @returns Promise if callback returns Promise, void otherwise
 */
from<T>(first: string, cb: ViewportCallback<T>): void | Promise<void>;

/**
 * Execute callback for breakpoints up to specified breakpoint
 * @param last - Last breakpoint name
 * @param cb - Callback function receiving breakpoint name
 * @returns Promise if callback returns Promise, void otherwise
 */
to<T>(last: string, cb: ViewportCallback<T>): void | Promise<void>;

/**
 * Execute callback for breakpoints between two specified breakpoints (inclusive)
 * @param first - First breakpoint name
 * @param last - Last breakpoint name
 * @param cb - Callback function receiving breakpoint name
 * @returns Promise if callback returns Promise, void otherwise
 */
between<T>(first: string, last: string, cb: ViewportCallback<T>): void | Promise<void>;

Iteration Examples:

// Test all breakpoints
viewport.each(name => {
  console.log(`Testing ${name}`);
  // Test logic here
});

// Test from tablet onwards
viewport.from("tablet", name => {
  // Tests tablet, desktop, etc.
});

// Test up to tablet
viewport.to("tablet", name => {
  // Tests mobile, tablet
});

// Test specific range
viewport.between("tablet", "desktop", name => {
  // Tests tablet, desktop
});

// Async support
viewport.each(async name => {
  await someAsyncTest();
});

Configuration

Viewport Configuration

Configure the plugin behavior in your Karma configuration file.

interface ViewportConfiguration {
  /** Context element selector (default: "#context") */
  context: string;
  /** Array of named breakpoints */
  breakpoints: ViewportBreakpoint[];
}

interface ViewportBreakpoint {
  /** Breakpoint name */
  name: string;
  /** Viewport dimensions */
  size: {
    width: number;
    height: number;
  };
}

Utility Functions

Utility functions exported by the karma-viewport module for advanced usage.

/**
 * Resolve relevant breakpoint range between two breakpoints
 * @param breakpoints - Array of viewport breakpoints
 * @param first - First breakpoint name
 * @param last - Last breakpoint name (defaults to first)
 * @returns Array of breakpoints in the specified range
 * @throws ReferenceError if breakpoint name is invalid
 */
function range(
  breakpoints: ViewportBreakpoint[], 
  first: string, 
  last?: string
): ViewportBreakpoint[];

Types

/**
 * Callback function type for viewport iteration methods
 */
type ViewportCallback<T> = (breakpoint: string) => T;

/**
 * Main Viewport class - available as global 'viewport' instance
 */
class Viewport {
  /** Viewport configuration (read-only) */
  readonly config: Readonly<ViewportConfiguration>;
  /** Target iframe element */
  readonly context: HTMLIFrameElement;
  
  /**
   * Create viewport resizer
   * @param config - Viewport configuration
   * @param parent - Initialization context (window)
   * @throws ReferenceError if context selector doesn't match HTMLIFrameElement
   */
  constructor(config: ViewportConfiguration, parent: Window);
  
  /** Set viewport to specific dimensions */
  set(width: number, height?: number): void;
  /** Set viewport to named breakpoint */
  set(breakpoint: string): void;
  /** Reset viewport to default size */
  reset(): void;
  /** Load and embed document into viewport */
  load(url: string, cb?: () => void): Promise<void>;
  /** Change viewport scroll offset */
  offset(x: number, y?: number): void;
  /** Execute callback for all breakpoints */
  each<T>(cb: ViewportCallback<T>): void | Promise<void>;
  /** Execute callback starting from specified breakpoint */
  from<T>(first: string, cb: ViewportCallback<T>): void | Promise<void>;
  /** Execute callback up to specified breakpoint */
  to<T>(last: string, cb: ViewportCallback<T>): void | Promise<void>;
  /** Execute callback between two specified breakpoints */
  between<T>(first: string, last: string, cb: ViewportCallback<T>): void | Promise<void>;
}

/**
 * Global viewport instance declaration
 */
declare const viewport: Viewport;

Error Handling

karma-viewport performs extensive parameter validation and throws specific errors:

/**
 * Common errors thrown by karma-viewport
 */

// Invalid breakpoint name in set(), each(), from(), to(), between() methods
ReferenceError: `Invalid breakpoint: ${inspect(name)}`

// Invalid context selector during initialization
ReferenceError: `No match for selector: ${inspect(config.context)}`

// Invalid viewport width (must be positive number)
TypeError: `Invalid breakpoint width: ${width}`

// Invalid viewport height (must be positive number or undefined)
TypeError: `Invalid breakpoint height: ${height}`

// Invalid viewport configuration object
TypeError: `Invalid viewport configuration: ${viewport}`

// Configuration validation errors (uses jsonschema validation)
TypeError: `Invalid viewport configuration: ${result.errors[0].stack}`

// Karma iframe configuration requirement
Error: "Invalid configuration: client.useIframe must be set to true or a different context selector must be given"

Parameter Validation Rules:

  • Viewport width must be a positive number > 0
  • Viewport height must be a positive number > 0 or undefined
  • Breakpoint names must exist in the configuration
  • Context selector must match an existing HTMLIFrameElement
  • Configuration must pass JSON schema validation

Browser Compatibility

  • Chrome
  • Firefox
  • Safari
  • Edge 13-15
  • IE 9-11

Requirements:

  • Karma must be configured with client.useIframe: true when using default context
  • The context iframe element must exist in the test environment