CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-ng-mocks

An Angular testing library for creating mock services, components, directives, pipes and modules in unit tests.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

testing-utilities.mddocs/

Testing Utilities and Helpers

Comprehensive testing utilities through the ngMocks object. Provides DOM interaction, element queries, instance access, event handling, and validation helpers for Angular testing.

Capabilities

Element Query Methods

Find and query DOM elements and components in test fixtures.

/**
 * Finds the first DebugElement of a component type
 * @param component - Component class to find
 * @param notFoundValue - Value to return if not found
 * @returns Found DebugElement or notFoundValue
 */
function find<T>(component: Type<T>): MockedDebugElement<T>;
function find<T, D>(component: Type<T>, notFoundValue: D): D | MockedDebugElement<T>;

/**
 * Finds the first DebugElement of a component type within a root element
 * @param debugElement - Root element to search within
 * @param component - Component class to find
 * @param notFoundValue - Value to return if not found
 * @returns Found DebugElement or notFoundValue
 */
function find<T>(
  debugElement: MockedDebugElement | ComponentFixture<any> | undefined | null,
  component: Type<T>
): MockedDebugElement<T>;
function find<T, D>(
  debugElement: MockedDebugElement | ComponentFixture<any> | undefined | null,
  component: Type<T>,
  notFoundValue: D
): D | MockedDebugElement<T>;

/**
 * Finds the first DebugElement matching a CSS selector
 * @param cssSelector - CSS selector string or attribute selector
 * @param notFoundValue - Value to return if not found
 * @returns Found DebugElement or notFoundValue
 */
function find<T = any>(
  cssSelector: string | [string] | [string, string | number]
): MockedDebugElement<T>;
function find<T = any, D = undefined>(
  cssSelector: string | [string] | [string, string | number],
  notFoundValue: D
): D | MockedDebugElement<T>;

/**
 * Finds all DebugElements of a component type
 * @param component - Component class to find
 * @returns Array of found DebugElements
 */
function findAll<T>(component: Type<T>): Array<MockedDebugElement<T>>;
function findAll<T>(
  debugElement: MockedDebugElement | ComponentFixture<any> | undefined | null,
  component: Type<T>
): Array<MockedDebugElement<T>>;

/**
 * Finds all DebugElements matching a CSS selector
 * @param cssSelector - CSS selector string or attribute selector
 * @returns Array of found DebugElements
 */
function findAll<T = any>(
  cssSelector: string | [string] | [string, string | number]
): Array<MockedDebugElement<T>>;
function findAll<T = any>(
  debugElement: MockedDebugElement | ComponentFixture<any> | undefined | null,
  cssSelector: string | [string] | [string, string | number]
): Array<MockedDebugElement<T>>;

Usage Examples:

import { ngMocks } from "ng-mocks";

// Find component by type
const headerEl = ngMocks.find(HeaderComponent);
const headerInstance = headerEl.componentInstance;

// Find with fallback
const sidebarEl = ngMocks.find(SidebarComponent, null);
if (sidebarEl) {
  // Handle found element
}

// Find by CSS selector
const buttonEl = ngMocks.find('button.primary');
const linkEls = ngMocks.findAll('a[href]');

// Find by attribute
const dataEl = ngMocks.find(['data-testid', 'user-info']);
const allDataEls = ngMocks.findAll(['data-role']);

// Search within specific element
const nestedEl = ngMocks.find(fixture.debugElement, MyComponent);

Instance Access Methods

Access component instances and injected services.

/**
 * Gets an instance of a declaration from an element
 * @param elSelector - Element selector
 * @param provider - Declaration class or token
 * @param notFoundValue - Value to return if not found
 * @returns Instance or notFoundValue
 */
function get<T>(elSelector: DebugNodeSelector, provider: AnyDeclaration<T>): T;
function get<T, D>(
  elSelector: DebugNodeSelector, 
  provider: AnyDeclaration<T>, 
  notFoundValue: D
): D | T;

/**
 * Gets an instance from TestBed
 * @param provider - Declaration class or token
 * @returns Instance from TestBed
 */
function get<T>(provider: AnyDeclaration<T>): T;

/**
 * Finds the first instance of a declaration in the component tree
 * @param instanceClass - Declaration class or token
 * @param notFoundValue - Value to return if not found
 * @returns Found instance or notFoundValue
 */
function findInstance<T>(instanceClass: AnyDeclaration<T>): T;
function findInstance<T, D>(instanceClass: AnyDeclaration<T>, notFoundValue: D): D | T;
function findInstance<T>(
  elSelector: DebugNodeSelector, 
  instanceClass: AnyDeclaration<T>
): T;
function findInstance<T, D>(
  elSelector: DebugNodeSelector, 
  instanceClass: AnyDeclaration<T>, 
  notFoundValue: D
): D | T;

/**
 * Finds all instances of a declaration in the component tree
 * @param instanceClass - Declaration class or token
 * @returns Array of found instances
 */
function findInstances<T>(instanceClass: AnyDeclaration<T>): T[];
function findInstances<T>(
  elSelector: DebugNodeSelector, 
  instanceClass: AnyDeclaration<T>
): T[];

Usage Examples:

import { ngMocks } from "ng-mocks";

// Get service from TestBed
const authService = ngMocks.get(AuthService);

// Get component instance from element
const headerEl = ngMocks.find(HeaderComponent);
const headerService = ngMocks.get(headerEl, HeaderService);

// Find service instance anywhere in component tree
const dataService = ngMocks.findInstance(DataService);

// Find with fallback
const optionalService = ngMocks.findInstance(OptionalService, null);

// Find all instances
const allServices = ngMocks.findInstances(LoggingService);

Input and Output Access

Access component inputs and outputs without knowing the specific component.

/**
 * Gets an input value from a component
 * @param elSelector - Element selector
 * @param input - Input property name
 * @param notFoundValue - Value to return if not found
 * @returns Input value or notFoundValue
 */
function input<T = any>(elSelector: DebugNodeSelector, input: string): T;
function input<T = any, D = undefined>(
  elSelector: DebugNodeSelector, 
  input: string, 
  notFoundValue: D
): D | T;

/**
 * Gets an output EventEmitter from a component
 * @param elSelector - Element selector  
 * @param output - Output property name
 * @param notFoundValue - Value to return if not found
 * @returns EventEmitter or notFoundValue
 */
function output<T = any>(elSelector: DebugNodeSelector, output: string): EventEmitter<T>;
function output<T = any, D = undefined>(
  elSelector: DebugNodeSelector, 
  output: string, 
  notFoundValue: D
): D | EventEmitter<T>;

Usage Examples:

import { ngMocks } from "ng-mocks";

// Get input values
const userEl = ngMocks.find(UserComponent);
const userName = ngMocks.input(userEl, 'name');
const userAge = ngMocks.input(userEl, 'age', 0);

// Get output emitters
const clickEmitter = ngMocks.output(userEl, 'click');
const changeEmitter = ngMocks.output(userEl, 'change', null);

// Subscribe to outputs
clickEmitter.subscribe(data => {
  console.log('User clicked:', data);
});

DOM Interaction Methods

Interact with DOM elements and trigger events.

/**
 * Simulates a click on an element
 * @param elSelector - Element or selector
 * @param payload - Optional mouse event properties
 */
function click(
  elSelector: HTMLElement | DebugNodeSelector, 
  payload?: Partial<MouseEvent>
): void;

/**
 * Triggers a custom event on an element
 * @param elSelector - Element or selector
 * @param event - Event object or event name
 * @param payload - Optional event properties
 */
function trigger(elSelector: DebugNodeSelector, event: Event): void;
function trigger(
  elSelector: HTMLElement | DebugNodeSelector,
  event: string,
  payload?: Partial<UIEvent | KeyboardEvent | MouseEvent | TouchEvent>
): void;

/**
 * Creates properly formatted events
 * @param event - Event type string
 * @param init - Event initialization options
 * @param overrides - Property overrides
 * @returns Created event object
 */
function event(
  event: string,
  init?: EventInit,
  overrides?: Partial<UIEvent | KeyboardEvent | MouseEvent | TouchEvent | Event>
): Event;

/**
 * Triggers ControlValueAccessor changes
 * @param elSelector - Element selector
 * @param value - New value
 * @param methodName - CVA method name to call
 */
function change(elSelector: DebugNodeSelector, value: any, methodName?: string): void;

/**
 * Triggers ControlValueAccessor touch
 * @param elSelector - Element selector  
 * @param methodName - CVA method name to call
 */
function touch(elSelector: DebugNode | DebugNodeSelector, methodName?: string): void;

Usage Examples:

import { ngMocks } from "ng-mocks";

// Click a button
const buttonEl = ngMocks.find('button.submit');
ngMocks.click(buttonEl);

// Click with custom payload
ngMocks.click(buttonEl, { 
  ctrlKey: true, 
  clientX: 100, 
  clientY: 200 
});

// Trigger keyboard events
ngMocks.trigger(inputEl, 'keydown', { key: 'Enter' });
ngMocks.trigger(inputEl, 'keydown.control.shift.z');

// Trigger custom events
const customEvent = ngMocks.event('custom-event', {}, { detail: { data: 'test' } });
ngMocks.trigger(elementEl, customEvent);

// Form control interactions
ngMocks.change(inputEl, 'new value');
ngMocks.touch(inputEl);

Template and Structural Directive Utilities

Work with ng-container, ng-template, and structural directives.

/**
 * Finds DebugNodes for ng-container or ng-template elements
 * @param selector - Component type or CSS selector
 * @param notFoundValue - Value to return if not found
 * @returns Found DebugNode or notFoundValue
 */
function reveal<T>(selector: AnyType<T>): MockedDebugNode<T> | MockedDebugElement<T>;
function reveal<T, D>(
  selector: AnyType<T>, 
  notFoundValue: D
): D | MockedDebugNode<T> | MockedDebugElement<T>;
function reveal<T = any>(
  selector: string | [string] | [string, any]
): MockedDebugNode<T> | MockedDebugElement<T>;
function reveal<T = any, D = undefined>(
  selector: string | [string] | [string, any],
  notFoundValue: D
): D | MockedDebugNode<T> | MockedDebugElement<T>;

/**
 * Finds all DebugNodes for ng-container or ng-template elements
 * @param selector - Component type or CSS selector
 * @returns Array of found DebugNodes
 */
function revealAll<T>(selector: AnyType<T>): Array<MockedDebugNode<T> | MockedDebugElement<T>>;
function revealAll<T = any>(
  selector: string | [string] | [string, any]
): Array<MockedDebugNode<T> | MockedDebugElement<T>>;

/**
 * Finds TemplateRef instances for rendering
 * @param elSelector - Element selector
 * @param selector - Template selector
 * @param notFoundValue - Value to return if not found
 * @returns TemplateRef or notFoundValue
 */
function findTemplateRef<T = any, D = undefined>(
  elSelector: DebugNodeSelector,
  selector: string | [string] | [string, any] | AnyType<any>,
  notFoundValue: D
): D | TemplateRef<T>;

/**
 * Renders templates or structural directives
 * @param instance - Component instance
 * @param template - TemplateRef or DebugNode to render
 * @param $implicit - Template context $implicit value
 * @param variables - Template context variables
 */
function render(
  instance: object,
  template: TemplateRef<any> | DebugNode,
  $implicit?: any,
  variables?: Record<keyof any, any>
): void;

/**
 * Hides rendered templates or structural directives
 * @param instance - Component instance
 * @param tpl - TemplateRef or DebugNode to hide
 */
function hide(instance: object, tpl?: TemplateRef<any> | DebugNode): void;

Usage Examples:

import { ngMocks } from "ng-mocks";

// Find structural directive containers
const ngIfEl = ngMocks.reveal(['structural', 'ngIf']);
const ngForEls = ngMocks.revealAll(['structural', 'ngFor']);

// Work with templates  
const templateRef = ngMocks.findTemplateRef(parentEl, TemplateDirective);
const component = ngMocks.get(parentEl, MyComponent);

// Render template with context
ngMocks.render(component, templateRef, 'implicit value', {
  user: { name: 'John' },
  index: 0
});

// Hide template
ngMocks.hide(component, templateRef);

Utility and Helper Methods

Additional utility methods for testing support.

/**
 * Creates stub methods on instances
 * @param instance - Object to stub
 * @param name - Property name to stub  
 * @param style - Accessor style ('get' or 'set')
 * @returns Stubbed function
 */
function stub<T = MockedFunction, I = any>(
  instance: I, 
  name: keyof I, 
  style?: 'get' | 'set'
): T;

/**
 * Applies partial overrides to an instance
 * @param instance - Object to modify
 * @param overrides - Properties to override
 * @returns Modified instance
 */
function stub<I extends object>(instance: I, overrides: Partial<I>): I;

/**
 * Crawls DOM tree correctly handling Angular structures
 * @param elSelector - Root element selector
 * @param callback - Function called for each node
 * @param includeTextNodes - Whether to include text nodes
 */
function crawl(
  elSelector: DebugNodeSelector,
  callback: (
    node: MockedDebugNode | MockedDebugElement,
    parent?: MockedDebugNode | MockedDebugElement
  ) => boolean | void,
  includeTextNodes?: boolean
): void;

/**
 * Formats HTML for readable output
 * @param html - Element, fixture, or HTML string
 * @param outer - Whether to include outer HTML
 * @returns Formatted HTML string
 */
function formatHtml(html: any, outer?: boolean): string;

/**
 * Formats text content for readable output
 * @param text - Element, fixture, or text string
 * @param outer - Whether to include outer text
 * @returns Formatted text string
 */
function formatText(text: any, outer?: boolean): string;

Usage Examples:

import { ngMocks } from "ng-mocks";

// Stub methods
const component = ngMocks.get(MyComponent);
const saveSpy = ngMocks.stub(component, 'save');
const getUserSpy = ngMocks.stub(component, 'user', 'get');

// Apply overrides
ngMocks.stub(component, {
  isEnabled: true,
  getData: () => ({ test: 'data' })
});

// Format HTML for assertions
const fixture = MockRender(MyComponent);
const html = ngMocks.formatHtml(fixture);
expect(html).toContain('<my-component>');

// Crawl DOM structure
ngMocks.crawl(fixture.debugElement, (node) => {
  if (node.componentInstance) {
    console.log('Found component:', node.componentInstance.constructor.name);
  }
});

docs

configuration.md

index.md

mock-builder.md

mock-creation.md

mock-instance.md

mock-render.md

testing-utilities.md

tile.json