or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

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

0

# ng-mocks

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: ng-mocks

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install ng-mocks --save-dev`

10

11

## Core Imports

12

13

```typescript

14

import {

15

MockBuilder,

16

MockRender,

17

MockComponent,

18

MockService,

19

MockModule,

20

ngMocks

21

} from "ng-mocks";

22

```

23

24

For CommonJS:

25

26

```javascript

27

const {

28

MockBuilder,

29

MockRender,

30

MockComponent,

31

MockService,

32

MockModule,

33

ngMocks

34

} = require("ng-mocks");

35

```

36

37

## Basic Usage

38

39

```typescript

40

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

41

42

// Mock a component for testing

43

@Component({

44

selector: 'app-test',

45

template: '<child-component [data]="inputData"></child-component>'

46

})

47

class TestComponent {

48

inputData = 'test data';

49

}

50

51

// Create mocks and render

52

beforeEach(() => {

53

return MockBuilder(TestComponent)

54

.mock(ChildComponent)

55

.build();

56

});

57

58

it('should render with mocked child', () => {

59

const fixture = MockRender(TestComponent);

60

const childEl = ngMocks.find(ChildComponent);

61

62

expect(childEl).toBeDefined();

63

expect(ngMocks.input(childEl, 'data')).toBe('test data');

64

});

65

```

66

67

## Architecture

68

69

ng-mocks is built around several key architectural patterns:

70

71

- **MockBuilder**: Advanced test environment configuration with fine-grained control over what to keep, mock, or exclude

72

- **Mock Creation Functions**: Individual functions for creating mocks of specific Angular constructs (components, services, etc.)

73

- **MockRender**: Component rendering system that supports both real and string templates with fixture management

74

- **ngMocks Helper**: Comprehensive utility object with 50+ methods for DOM interaction, element queries, and instance access

75

- **MockInstance**: Runtime customization system for modifying mock behavior during test execution

76

- **Type Safety**: Full TypeScript integration with accurate type inference and generic preservation

77

78

## Capabilities

79

80

### Test Environment Configuration

81

82

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

83

84

```typescript { .api }

85

function MockBuilder(

86

keepDeclaration?: MockBuilderParam | MockBuilderParam[] | null | undefined,

87

itsModuleAndDependenciesToMock?: MockBuilderParam | MockBuilderParam[] | null | undefined

88

): IMockBuilderExtended;

89

90

interface IMockBuilder extends Promise<IMockBuilderResult> {

91

keep(def: any, config?: IMockBuilderConfigAll & IMockBuilderConfigModule): this;

92

mock(def: any, config?: IMockBuilderConfig): this;

93

exclude(def: any): this;

94

provide(def: IMockBuilderProvider): this;

95

replace(source: AnyType<any>, destination: AnyType<any>, config?: IMockBuilderConfigAll & IMockBuilderConfigModule): this;

96

build(): TestModuleMetadata;

97

}

98

```

99

100

[Test Environment Configuration](./mock-builder.md)

101

102

### Component Rendering and Testing

103

104

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

105

106

```typescript { .api }

107

function MockRender<MComponent, TComponent extends object = Record<keyof any, any>>(

108

template: AnyType<MComponent> | string,

109

params?: TComponent,

110

detectChangesOrOptions?: boolean | IMockRenderOptions

111

): MockedComponentFixture<MComponent, TComponent>;

112

113

interface MockedComponentFixture<C = any, F = DefaultRenderComponent<C>> extends ComponentFixture<F> {

114

point: MockedDebugElement<C>;

115

}

116

```

117

118

[Component Rendering](./mock-render.md)

119

120

### Mock Creation and Management

121

122

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

123

124

```typescript { .api }

125

function MockComponent<T>(component: AnyType<T>): AnyType<T>;

126

function MockService<T>(service: AnyType<T>, overrides?: Partial<T>): T;

127

function MockModule<T>(module: AnyType<T>): AnyType<T>;

128

function MockDirective<T>(directive: AnyType<T>): AnyType<T>;

129

function MockPipe<T>(pipe: AnyType<T>, transform?: any): AnyType<T>;

130

```

131

132

[Mock Creation](./mock-creation.md)

133

134

### Testing Utilities and Helpers

135

136

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

137

138

```typescript { .api }

139

const ngMocks: {

140

find<T>(component: Type<T>): MockedDebugElement<T>;

141

findAll<T>(component: Type<T>): Array<MockedDebugElement<T>>;

142

get<T>(provider: AnyDeclaration<T>): T;

143

input<T>(elSelector: DebugNodeSelector, input: string): T;

144

output<T>(elSelector: DebugNodeSelector, output: string): EventEmitter<T>;

145

click(elSelector: HTMLElement | DebugNodeSelector, payload?: Partial<MouseEvent>): void;

146

trigger(elSelector: DebugNodeSelector, event: string | Event, payload?: any): void;

147

stub<T, I>(instance: I, name: keyof I, style?: 'get' | 'set'): T;

148

// ... 40+ additional utility methods

149

};

150

```

151

152

[Testing Utilities](./testing-utilities.md)

153

154

### Runtime Mock Customization

155

156

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

157

158

```typescript { .api }

159

function MockInstance<T extends object, K extends keyof T, S extends () => T[K]>(

160

instance: AnyType<T>,

161

name: K,

162

stub: S,

163

encapsulation: 'get'

164

): S;

165

166

function MockInstance<T extends object, K extends keyof T, S extends T[K]>(

167

instance: AnyType<T>,

168

name: K,

169

stub: S

170

): S;

171

172

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

173

```

174

175

[Runtime Customization](./mock-instance.md)

176

177

### Configuration and Global Settings

178

179

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

180

181

```typescript { .api }

182

const ngMocks: {

183

autoSpy(type: 'jasmine' | 'jest' | 'default' | 'reset' | CustomMockFunction): void;

184

defaultConfig<T>(token: string | AnyDeclaration<T>, config?: IMockBuilderConfig): void;

185

defaultMock<T>(def: AnyType<T>, handler?: (value: T, injector: Injector) => void | Partial<T>, config?: IMockBuilderConfig): void;

186

globalKeep(source: AnyDeclaration<any>, recursively?: boolean): void;

187

globalMock(source: AnyDeclaration<any>, recursively?: boolean): void;

188

globalExclude(source: AnyDeclaration<any>, recursively?: boolean): void;

189

config(config: { mockRenderCacheSize?: number | null; onMockBuilderMissingDependency?: 'throw' | 'warn' | 'i-know-but-disable' | null; }): void;

190

};

191

```

192

193

[Configuration](./configuration.md)

194

195

### Core Utility Functions

196

197

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

198

199

```typescript { .api }

200

function getTestBedInjection<T>(token: AnyDeclaration<T>): T;

201

function getInjection<T>(token: AnyDeclaration<T>): T;

202

function getMockedNgDefOf<T>(def: AnyType<T>): T;

203

function getSourceOfMock<T>(def: AnyType<T>): AnyType<T>;

204

function isMockControlValueAccessor(def: any): boolean;

205

function isMockNgDef(def: any): boolean;

206

function isMockOf<T>(mockDef: any, def: AnyType<T>): boolean;

207

function isMockValidator(def: any): boolean;

208

function isMockedNgDefOf<T>(mockDef: any, def: AnyType<T>): boolean;

209

function isNgDef(def: any): boolean;

210

function isNgInjectionToken(def: any): boolean;

211

```

212

213

### Core Classes and Interfaces

214

215

Base classes and interfaces for mock implementations.

216

217

```typescript { .api }

218

class Mock {

219

// Base mock class with configuration methods

220

}

221

222

class MockControlValueAccessor {

223

// Mock implementation of ControlValueAccessor

224

}

225

226

class MockValidator {

227

// Mock implementation of validators

228

}

229

230

class LegacyControlValueAccessor {

231

// Legacy CVA support

232

}

233

```

234

235

## Types

236

237

```typescript { .api }

238

type AnyType<T> = new (...args: any[]) => T;

239

type AnyDeclaration<T> = AnyType<T> | InjectionToken<T>;

240

type DebugNodeSelector = string | [string] | [string, string | number] | DebugNode | ComponentFixture<any>;

241

242

interface MockedDebugElement<T = any> extends DebugElement {

243

componentInstance: T;

244

}

245

246

interface MockedDebugNode<T = any> extends DebugNode {

247

componentInstance: T;

248

}

249

250

interface IMockRenderOptions {

251

detectChanges?: boolean;

252

providers?: NgModule['providers'];

253

reset?: boolean;

254

viewProviders?: NgModule['providers'];

255

}

256

257

interface IMockBuilderConfig {

258

dependency?: boolean;

259

export?: boolean;

260

shallow?: boolean;

261

onRoot?: boolean;

262

exportAll?: boolean;

263

render?: boolean | { $implicit?: any; variables?: Record<keyof any, any>; };

264

precise?: boolean;

265

}

266

267

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

268

type CustomMockFunction = (mockName: string) => MockedFunction;

269

```