An Angular testing library for creating mock services, components, directives, pipes and modules in unit tests.
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Global configuration system for default behaviors, spy integration, and testing framework compatibility. Provides comprehensive control over ng-mocks behavior across all tests.
Configure automatic spy creation for different testing frameworks.
/**
* Configures automatic spy creation for different frameworks
* @param type - Framework type or 'reset' to disable
*/
function autoSpy(type: 'jasmine' | 'jest' | 'default' | 'reset'): void;
/**
* Configures automatic spy creation with custom function
* @param type - Custom spy factory function
*/
function autoSpy(type: CustomMockFunction): void;
/**
* Custom spy factory function type
*/
type CustomMockFunction = (mockName: string) => MockedFunction;
type MockedFunction = (...args: any[]) => any;Usage Examples:
import { ngMocks } from "ng-mocks";
// Configure for Jasmine
ngMocks.autoSpy('jasmine');
// Configure for Jest
ngMocks.autoSpy('jest');
// Custom spy factory
ngMocks.autoSpy((name: string) => {
const spy = jasmine.createSpy(name);
spy.and.returnValue(undefined);
return spy;
});
// Disable auto-spy
ngMocks.autoSpy('reset');Set default configurations and behaviors for mock declarations.
/**
* Sets default configuration for a declaration type
* @param token - Declaration class or string token
* @param config - Default MockBuilder configuration
*/
function defaultConfig<T>(token: string | AnyDeclaration<T>, config?: IMockBuilderConfig): void;
/**
* Sets default mock behavior for injection tokens
* @param token - InjectionToken to configure
* @param handler - Function to customize mock instances
* @param config - Additional configuration
*/
function defaultMock<T>(
token: InjectionToken<T>,
handler?: (value: undefined | T, injector: Injector) => undefined | Partial<T>,
config?: IMockBuilderConfig
): void;
/**
* Sets default mock behavior for string tokens
* @param token - String token to configure
* @param handler - Function to customize mock instances
* @param config - Additional configuration
*/
function defaultMock<T = any>(
token: string,
handler?: (value: undefined | T, injector: Injector) => undefined | Partial<T>,
config?: IMockBuilderConfig
): void;
/**
* Sets default mock behavior for declaration classes
* @param def - Declaration class to configure
* @param handler - Function to customize mock instances
* @param config - Additional configuration
*/
function defaultMock<T>(
def: AnyType<T>,
handler?: (value: T, injector: Injector) => void | Partial<T>,
config?: IMockBuilderConfig
): void;
/**
* Sets default mock behavior for multiple declarations
* @param defs - Array of declarations to configure
* @param handler - Function to customize mock instances
* @param config - Additional configuration
*/
function defaultMock<T = any>(
defs: Array<AnyDeclaration<T>>,
handler?: (value: undefined | T, injector: Injector) => undefined | Partial<T>,
config?: IMockBuilderConfig
): void;Usage Examples:
import { ngMocks } from "ng-mocks";
// Set default configuration flags
ngMocks.defaultConfig(MyComponent, { shallow: true });
ngMocks.defaultConfig(SharedModule, { exportAll: true });
// Set default mock behavior for services
ngMocks.defaultMock(AuthService, (instance) => ({
isAuthenticated: true,
user: { id: 1, name: 'Test User' }
}));
// Configure injection tokens
ngMocks.defaultMock(API_URL, () => 'http://localhost:3000');
// Configure multiple services at once
ngMocks.defaultMock([UserService, OrderService], (instance, injector) => {
const httpClient = injector.get(HttpClient);
return {
http: httpClient,
loading: false
};
});Configure which declarations should always be kept, mocked, or excluded across all tests.
/**
* Globally excludes declarations from all mocks
* @param source - Declaration to exclude
* @param recursively - Whether to apply recursively to dependencies
*/
function globalExclude(source: AnyDeclaration<any>, recursively?: boolean): void;
/**
* Globally keeps declarations in all mocks (never mock them)
* @param source - Declaration to keep
* @param recursively - Whether to apply recursively to dependencies
*/
function globalKeep(source: AnyDeclaration<any>, recursively?: boolean): void;
/**
* Globally mocks declarations even when they would be kept
* @param source - Declaration to mock
* @param recursively - Whether to apply recursively to dependencies
*/
function globalMock(source: AnyDeclaration<any>, recursively?: boolean): void;
/**
* Globally replaces one declaration with another across all mocks
* @param source - Declaration to replace
* @param destination - Replacement declaration
*/
function globalReplace(source: AnyType<any>, destination: AnyType<any>): void;
/**
* Removes global configuration for a declaration
* @param source - Declaration to reset
* @param recursively - Whether to apply recursively to dependencies
*/
function globalWipe(source: AnyDeclaration<any>, recursively?: boolean): void;Usage Examples:
import { ngMocks } from "ng-mocks";
// Always keep common Angular modules
ngMocks.globalKeep(CommonModule, true);
ngMocks.globalKeep(FormsModule, true);
ngMocks.globalKeep(ReactiveFormsModule, true);
// Always mock HTTP-related modules
ngMocks.globalMock(HttpClientModule, true);
// Always exclude problematic modules
ngMocks.globalExclude(ProblematicThirdPartyModule, true);
// Global replacements for testing
ngMocks.globalReplace(BrowserAnimationsModule, NoopAnimationsModule);
// Remove global configuration
ngMocks.globalWipe(HttpClientModule);
ngMocks.globalWipe(CommonModule, true);Configure ng-mocks behavior and error handling.
/**
* Configures ng-mocks system behavior
* @param config - Configuration object
*/
function config(config: {
/** Maximum number of MockRender fixtures to cache (null = unlimited) */
mockRenderCacheSize?: number | null;
/** Behavior when MockBuilder encounters missing dependencies */
onMockBuilderMissingDependency?: 'throw' | 'warn' | 'i-know-but-disable' | null;
/** Behavior when MockInstance restore is needed */
onMockInstanceRestoreNeed?: 'throw' | 'warn' | 'i-know-but-disable' | null;
/** Behavior when TestBed flush is needed */
onTestBedFlushNeed?: 'throw' | 'warn' | 'i-know-but-disable' | null;
}): void;Usage Examples:
import { ngMocks } from "ng-mocks";
// Configure for production-like testing
ngMocks.config({
mockRenderCacheSize: 10,
onMockBuilderMissingDependency: 'warn',
onMockInstanceRestoreNeed: 'warn',
onTestBedFlushNeed: 'throw'
});
// Disable cache for memory-constrained environments
ngMocks.config({
mockRenderCacheSize: 0
});
// Strict mode - fail fast on issues
ngMocks.config({
onMockBuilderMissingDependency: 'throw',
onMockInstanceRestoreNeed: 'throw',
onTestBedFlushNeed: 'throw'
});Control console output and error handling during tests.
/**
* Suppresses console methods during tests
* @param args - Console method names to suppress
*/
function ignoreOnConsole(...args: Array<keyof typeof console>): void;
/**
* Causes console methods to throw errors during tests
* @param args - Console method names to make throw
*/
function throwOnConsole(...args: Array<keyof typeof console>): void;Usage Examples:
import { ngMocks } from "ng-mocks";
// Suppress console warnings and logs during tests
ngMocks.ignoreOnConsole('warn', 'log');
// Make console errors throw exceptions
ngMocks.throwOnConsole('error');
// Ignore all console output
ngMocks.ignoreOnConsole('log', 'warn', 'error', 'info', 'debug');Optimize performance with caching and reuse strategies.
/**
* Enables TestBed reuse between tests for better performance
*/
function faster(): void;
/**
* Resets ng-mocks internal cache
*/
function reset(): void;
/**
* Flushes TestBed state
*/
function flushTestBed(): void;Usage Examples:
import { ngMocks } from "ng-mocks";
// Enable faster test execution
beforeAll(() => {
ngMocks.faster();
});
// Reset between test suites
afterAll(() => {
ngMocks.reset();
ngMocks.flushTestBed();
});
// Clean up in specific tests
afterEach(() => {
if (testNeedsCleanup) {
ngMocks.flushTestBed();
}
});Common configuration patterns for different testing scenarios.
Basic Test Setup:
// spec-helper.ts or test setup file
import { ngMocks } from "ng-mocks";
// Configure spy framework
ngMocks.autoSpy('jasmine');
// Global module configuration
ngMocks.globalKeep(CommonModule, true);
ngMocks.globalKeep(FormsModule, true);
ngMocks.globalReplace(BrowserAnimationsModule, NoopAnimationsModule);
// Suppress non-critical console output
ngMocks.ignoreOnConsole('warn');
// Enable performance optimizations
ngMocks.faster();Enterprise Application Setup:
// Configure for large applications
ngMocks.config({
mockRenderCacheSize: 50,
onMockBuilderMissingDependency: 'warn'
});
// Always keep core modules
ngMocks.globalKeep(SharedModule, true);
ngMocks.globalKeep(CoreModule, true);
ngMocks.globalKeep(MaterialModule, true);
// Mock external service modules
ngMocks.globalMock(HttpClientModule, true);
ngMocks.globalMock(AngularFireModule, true);
// Standard service mocks
ngMocks.defaultMock(AuthService, () => ({
isAuthenticated: true,
user: { id: 1, name: 'Test User', role: 'user' }
}));
ngMocks.defaultMock(ConfigService, () => ({
apiUrl: 'http://localhost:3000',
environment: 'test'
}));Library Testing Setup:
// Configure for library testing
ngMocks.config({
onMockBuilderMissingDependency: 'throw', // Strict dependency checking
onTestBedFlushNeed: 'throw'
});
// Keep only Angular core modules
ngMocks.globalKeep(CommonModule);
ngMocks.globalKeep(FormsModule);
// Mock everything else
ngMocks.globalMock(HttpClientModule, true);
ngMocks.globalMock(RouterModule, true);Integration Test Setup:
// More permissive for integration tests
ngMocks.config({
onMockBuilderMissingDependency: 'i-know-but-disable',
mockRenderCacheSize: 5 // Lower cache for integration tests
});
// Keep more real modules for integration
ngMocks.globalKeep(HttpClientModule);
ngMocks.globalKeep(RouterModule);
ngMocks.globalKeep(SharedModule, true);
// Only mock external dependencies
ngMocks.globalMock(ThirdPartyApiModule, true);