or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

configuration.mdindex.mdmock-builder.mdmock-creation.mdmock-instance.mdmock-render.mdtesting-utilities.md
tile.json

tessl/npm-ng-mocks

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

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/ng-mocks@14.13.x

To install, run

npx @tessl/cli install tessl/npm-ng-mocks@14.13.0

index.mddocs/

ng-mocks

ng-mocks is a comprehensive Angular testing library that simplifies unit testing by enabling developers to create mock implementations of components, services, directives, pipes, and modules. It offers shallow rendering capabilities, precise stubbing mechanisms to eliminate child dependencies, and supports both Jasmine and Jest testing frameworks across Angular versions 5-20.

Package Information

  • Package Name: ng-mocks
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install ng-mocks --save-dev

Core Imports

import { 
  MockBuilder, 
  MockRender, 
  MockComponent, 
  MockService, 
  MockModule,
  ngMocks 
} from "ng-mocks";

For CommonJS:

const { 
  MockBuilder, 
  MockRender, 
  MockComponent, 
  MockService, 
  MockModule,
  ngMocks 
} = require("ng-mocks");

Basic Usage

import { MockBuilder, MockRender, MockComponent, ngMocks } from "ng-mocks";

// Mock a component for testing
@Component({
  selector: 'app-test',
  template: '<child-component [data]="inputData"></child-component>'
})
class TestComponent {
  inputData = 'test data';
}

// Create mocks and render
beforeEach(() => {
  return MockBuilder(TestComponent)
    .mock(ChildComponent)
    .build();
});

it('should render with mocked child', () => {
  const fixture = MockRender(TestComponent);
  const childEl = ngMocks.find(ChildComponent);
  
  expect(childEl).toBeDefined();
  expect(ngMocks.input(childEl, 'data')).toBe('test data');
});

Architecture

ng-mocks is built around several key architectural patterns:

  • MockBuilder: Advanced test environment configuration with fine-grained control over what to keep, mock, or exclude
  • Mock Creation Functions: Individual functions for creating mocks of specific Angular constructs (components, services, etc.)
  • MockRender: Component rendering system that supports both real and string templates with fixture management
  • ngMocks Helper: Comprehensive utility object with 50+ methods for DOM interaction, element queries, and instance access
  • MockInstance: Runtime customization system for modifying mock behavior during test execution
  • Type Safety: Full TypeScript integration with accurate type inference and generic preservation

Capabilities

Test Environment Configuration

Advanced test setup and configuration using MockBuilder for precise control over testing environment. Supports dependency management, provider configuration, and module customization.

function MockBuilder(
  keepDeclaration?: MockBuilderParam | MockBuilderParam[] | null | undefined,
  itsModuleAndDependenciesToMock?: MockBuilderParam | MockBuilderParam[] | null | undefined
): IMockBuilderExtended;

interface IMockBuilder extends Promise<IMockBuilderResult> {
  keep(def: any, config?: IMockBuilderConfigAll & IMockBuilderConfigModule): this;
  mock(def: any, config?: IMockBuilderConfig): this;
  exclude(def: any): this;
  provide(def: IMockBuilderProvider): this;
  replace(source: AnyType<any>, destination: AnyType<any>, config?: IMockBuilderConfigAll & IMockBuilderConfigModule): this;
  build(): TestModuleMetadata;
}

Test Environment Configuration

Component Rendering and Testing

Component rendering system with MockRender for creating test fixtures, accessing component instances, and managing lifecycle. Provides powerful fixture management with type-safe access.

function MockRender<MComponent, TComponent extends object = Record<keyof any, any>>(
  template: AnyType<MComponent> | string,
  params?: TComponent,
  detectChangesOrOptions?: boolean | IMockRenderOptions
): MockedComponentFixture<MComponent, TComponent>;

interface MockedComponentFixture<C = any, F = DefaultRenderComponent<C>> extends ComponentFixture<F> {
  point: MockedDebugElement<C>;
}

Component Rendering

Mock Creation and Management

Individual mock creation functions for all Angular constructs. Provides precise control over mock behavior and supports both automatic and manual mock configuration.

function MockComponent<T>(component: AnyType<T>): AnyType<T>;
function MockService<T>(service: AnyType<T>, overrides?: Partial<T>): T;
function MockModule<T>(module: AnyType<T>): AnyType<T>;
function MockDirective<T>(directive: AnyType<T>): AnyType<T>;
function MockPipe<T>(pipe: AnyType<T>, transform?: any): AnyType<T>;

Mock Creation

Testing Utilities and Helpers

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

const ngMocks: {
  find<T>(component: Type<T>): MockedDebugElement<T>;
  findAll<T>(component: Type<T>): Array<MockedDebugElement<T>>;
  get<T>(provider: AnyDeclaration<T>): T;
  input<T>(elSelector: DebugNodeSelector, input: string): T;
  output<T>(elSelector: DebugNodeSelector, output: string): EventEmitter<T>;
  click(elSelector: HTMLElement | DebugNodeSelector, payload?: Partial<MouseEvent>): void;
  trigger(elSelector: DebugNodeSelector, event: string | Event, payload?: any): void;
  stub<T, I>(instance: I, name: keyof I, style?: 'get' | 'set'): T;
  // ... 40+ additional utility methods
};

Testing Utilities

Runtime Mock Customization

Runtime mock instance customization with MockInstance for modifying behavior during test execution. Supports method stubbing, property overrides, and lifecycle management.

function MockInstance<T extends object, K extends keyof T, S extends () => T[K]>(
  instance: AnyType<T>,
  name: K,
  stub: S,
  encapsulation: 'get'
): S;

function MockInstance<T extends object, K extends keyof T, S extends T[K]>(
  instance: AnyType<T>,
  name: K,
  stub: S
): S;

function MockReset(...instances: Array<AnyType<any>>): void;

Runtime Customization

Configuration and Global Settings

Global configuration system for default behaviors, spy integration, and testing framework compatibility. Supports Jasmine, Jest, and custom spy implementations.

const ngMocks: {
  autoSpy(type: 'jasmine' | 'jest' | 'default' | 'reset' | CustomMockFunction): void;
  defaultConfig<T>(token: string | AnyDeclaration<T>, config?: IMockBuilderConfig): void;
  defaultMock<T>(def: AnyType<T>, handler?: (value: T, injector: Injector) => void | Partial<T>, config?: IMockBuilderConfig): void;
  globalKeep(source: AnyDeclaration<any>, recursively?: boolean): void;
  globalMock(source: AnyDeclaration<any>, recursively?: boolean): void;
  globalExclude(source: AnyDeclaration<any>, recursively?: boolean): void;
  config(config: { mockRenderCacheSize?: number | null; onMockBuilderMissingDependency?: 'throw' | 'warn' | 'i-know-but-disable' | null; }): void;
};

Configuration

Core Utility Functions

Essential utility functions for working with Angular declarations and dependency injection.

function getTestBedInjection<T>(token: AnyDeclaration<T>): T;
function getInjection<T>(token: AnyDeclaration<T>): T;
function getMockedNgDefOf<T>(def: AnyType<T>): T;
function getSourceOfMock<T>(def: AnyType<T>): AnyType<T>;
function isMockControlValueAccessor(def: any): boolean;
function isMockNgDef(def: any): boolean;
function isMockOf<T>(mockDef: any, def: AnyType<T>): boolean;
function isMockValidator(def: any): boolean;
function isMockedNgDefOf<T>(mockDef: any, def: AnyType<T>): boolean;
function isNgDef(def: any): boolean;
function isNgInjectionToken(def: any): boolean;

Core Classes and Interfaces

Base classes and interfaces for mock implementations.

class Mock {
  // Base mock class with configuration methods
}

class MockControlValueAccessor {
  // Mock implementation of ControlValueAccessor
}

class MockValidator {
  // Mock implementation of validators
}

class LegacyControlValueAccessor {
  // Legacy CVA support
}

Types

type AnyType<T> = new (...args: any[]) => T;
type AnyDeclaration<T> = AnyType<T> | InjectionToken<T>;
type DebugNodeSelector = string | [string] | [string, string | number] | DebugNode | ComponentFixture<any>;

interface MockedDebugElement<T = any> extends DebugElement {
  componentInstance: T;
}

interface MockedDebugNode<T = any> extends DebugNode {
  componentInstance: T;
}

interface IMockRenderOptions {
  detectChanges?: boolean;
  providers?: NgModule['providers'];
  reset?: boolean;
  viewProviders?: NgModule['providers'];
}

interface IMockBuilderConfig {
  dependency?: boolean;
  export?: boolean;
  shallow?: boolean;
  onRoot?: boolean;
  exportAll?: boolean;
  render?: boolean | { $implicit?: any; variables?: Record<keyof any, any>; };
  precise?: boolean;
}

type MockedFunction = (...args: any[]) => any;
type CustomMockFunction = (mockName: string) => MockedFunction;