An Angular testing library for creating mock services, components, directives, pipes and modules in unit tests.
npx @tessl/cli install tessl/npm-ng-mocks@14.13.0ng-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.
npm install ng-mocks --save-devimport {
MockBuilder,
MockRender,
MockComponent,
MockService,
MockModule,
ngMocks
} from "ng-mocks";For CommonJS:
const {
MockBuilder,
MockRender,
MockComponent,
MockService,
MockModule,
ngMocks
} = require("ng-mocks");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');
});ng-mocks is built around several key architectural patterns:
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 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>;
}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>;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
};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;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;
};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;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
}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;