New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

ng-mocks

Package Overview
Dependencies
Maintainers
1
Versions
175
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ng-mocks - npm Package Compare versions

Comparing version 9.2.0 to 9.3.0

dist/jasmine.d.ts

9

dist/lib/common/jit-reflector.d.ts
import { CompileReflector, ExternalReference } from '@angular/compiler';
import { Component } from '@angular/core';
export declare class JitReflector implements CompileReflector {

@@ -7,4 +6,4 @@ private readonly _reflectionCapabilities;

annotations(typeOrFunc: any): any[];
componentModuleUrl(type: any, cmpMetadata: Component): string;
guards(type: any): {
componentModuleUrl: (type: any) => string;
guards: () => {
[key: string]: any;

@@ -17,5 +16,5 @@ };

};
resolveExternalReference(ref: ExternalReference): any;
shallowAnnotations: (typeOrFunc: any) => any[];
resolveExternalReference: (ref: ExternalReference) => any;
shallowAnnotations: () => any[];
tryAnnotations(typeOrFunc: any): any[];
}

@@ -6,3 +6,8 @@ "use strict";

constructor() {
this.shallowAnnotations = (typeOrFunc) => { throw new Error('Not supported in JIT mode'); };
this.componentModuleUrl = (type) => `./${core_1.ɵstringify(type)}`;
this.guards = () => ({});
this.resolveExternalReference = (ref) => ref.runtime;
this.shallowAnnotations = () => {
throw new Error('Not supported in JIT mode');
};
this._reflectionCapabilities = new core_1.ɵReflectionCapabilities();

@@ -13,8 +18,2 @@ }

}
componentModuleUrl(type, cmpMetadata) {
return `./${core_1.ɵstringify(type)}`;
}
guards(type) {
return {};
}
hasLifecycleHook(type, lcProperty) {

@@ -29,5 +28,2 @@ return this._reflectionCapabilities.hasLifecycleHook(type, lcProperty);

}
resolveExternalReference(ref) {
return ref.runtime;
}
tryAnnotations(typeOrFunc) {

@@ -34,0 +30,0 @@ return this.annotations(typeOrFunc);

@@ -11,3 +11,3 @@ "use strict";

}
this[method] = mock_service_1.mockServiceHelper.mockFunction(this, method);
this[method] = mock_service_1.mockServiceHelper.mockFunction();
}

@@ -14,0 +14,0 @@ for (const output of this.__mockedOutputs) {

@@ -15,6 +15,7 @@ "use strict";

const common_1 = require("../common");
const decorate_1 = require("../common/decorate");
const reflect_1 = require("../common/reflect");
const cache = new Map();
function MockComponents(...components) {
return components.map((component) => MockComponent(component, undefined));
return components.map(component => MockComponent(component, undefined));
}

@@ -51,3 +52,4 @@ exports.MockComponents = MockComponents;

`;
}).join('');
})
.join('');
if (templateQueries) {

@@ -62,14 +64,13 @@ template = `

exportAs,
inputs,
outputs,
providers: [{
providers: [
{
multi: true,
provide: forms_1.NG_VALUE_ACCESSOR,
useExisting: core_1.forwardRef(() => ComponentMock)
useExisting: core_1.forwardRef(() => ComponentMock),
},
{
provide: component,
useExisting: core_1.forwardRef(() => ComponentMock)
}],
queries,
useExisting: core_1.forwardRef(() => ComponentMock),
},
],
selector,

@@ -100,2 +101,3 @@ template,

viewContainer.createEmbeddedView(templateRef, Object.assign(Object.assign({}, variables), { $implicit }));
changeDetector.detectChanges();
}

@@ -110,2 +112,5 @@ }

], ComponentMock);
decorate_1.decorateInputs(ComponentMock, inputs);
decorate_1.decorateOutputs(ComponentMock, outputs);
decorate_1.decorateQueries(ComponentMock, queries);
const mockedComponent = core_1.Component(options)(ComponentMock);

@@ -112,0 +117,0 @@ cache.set(component, mockedComponent);

@@ -16,3 +16,3 @@ "use strict";

const annotations = reflect_1.jitReflector.annotations(declaration);
if (annotations.find((annotation) => annotation.template !== undefined || annotation.templateUrl !== undefined)) {
if (annotations.find(annotation => annotation.template !== undefined || annotation.templateUrl !== undefined)) {
return mock_component_1.MockComponent(declaration);

@@ -19,0 +19,0 @@ }

@@ -17,2 +17,3 @@ "use strict";

const common_1 = require("../common");
const decorate_1 = require("../common/decorate");
const reflect_1 = require("../common/reflect");

@@ -29,11 +30,11 @@ const cache = new Map();

}
const { selector, exportAs, inputs, outputs } = reflect_1.directiveResolver.resolve(directive);
const { selector, exportAs, inputs, outputs, queries } = reflect_1.directiveResolver.resolve(directive);
const options = {
exportAs,
inputs,
outputs,
providers: [{
providers: [
{
provide: directive,
useExisting: core_1.forwardRef(() => DirectiveMock)
}],
useExisting: core_1.forwardRef(() => DirectiveMock),
},
],
selector,

@@ -65,2 +66,5 @@ };

], DirectiveMock);
decorate_1.decorateInputs(DirectiveMock, inputs);
decorate_1.decorateOutputs(DirectiveMock, outputs);
decorate_1.decorateQueries(DirectiveMock, queries);
const mockedDirective = core_1.Directive(options)(DirectiveMock);

@@ -67,0 +71,0 @@ cache.set(directive, mockedDirective);

import { DebugNode, Type } from '@angular/core';
import { MockedDebugElement } from '../mock-render';
import { MockedFunction } from '../mock-service';
export declare const MockHelper: {
getDirective: <T>(debugNode: DebugNode, directive: Type<T>) => T | undefined;
findDirective: <T_1>(debugNode: DebugNode, directive: Type<T_1>) => T_1 | undefined;
findDirectives: <T_2>(debugNode: DebugNode, directive: Type<T_2>) => T_2[];
find<T>(debugElement: MockedDebugElement<any>, component: Type<T>): null | MockedDebugElement<T>;
find<T = any>(debugElement: MockedDebugElement<any>, cssSelector: string): null | MockedDebugElement<T>;
findAll<T>(debugElement: MockedDebugElement<any>, component: Type<T>): Array<MockedDebugElement<T>>;
findAll<T = any>(debugElement: MockedDebugElement<any>, cssSelector: string): Array<MockedDebugElement<T>>;
findDirective<T>(debugNode: DebugNode, directive: Type<T>): undefined | T;
findDirectiveOrFail<T>(debugNode: DebugNode, directive: Type<T>): T;
findDirectives<T>(debugNode: DebugNode, directive: Type<T>): T[];
findOrFail<T>(debugElement: MockedDebugElement<any>, component: Type<T>): MockedDebugElement<T>;
findOrFail<T = any>(debugElement: MockedDebugElement<any>, cssSelector: string): MockedDebugElement<T>;
getDirective<T>(debugNode: DebugNode, directive: Type<T>): undefined | T;
getDirectiveOrFail<T>(debugNode: DebugNode, directive: Type<T>): T;
mockService<T = MockedFunction>(instance: any, name: string, style?: 'get' | 'set'): T;
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const platform_browser_1 = require("@angular/platform-browser");
const mock_service_1 = require("../mock-service");
function nestedCheck(result, node, callback) {

@@ -9,3 +11,3 @@ const element = callback(node);

const childNodes = node.childNodes ? node.childNodes : [];
childNodes.forEach((childNode) => {
childNodes.forEach(childNode => {
nestedCheck(result, childNode, callback);

@@ -15,2 +17,9 @@ });

exports.MockHelper = {
getDirectiveOrFail: (debugNode, directive) => {
const result = exports.MockHelper.getDirective(debugNode, directive);
if (!result) {
throw new Error(`Cannot find a directive via MockHelper.getDirectiveOrFail`);
}
return result;
},
getDirective: (debugNode, directive) => {

@@ -29,3 +38,3 @@ try {

}
const matches = debugNode.parent.queryAllNodes((node) => node.nativeNode === prevNode);
const matches = debugNode.parent.queryAllNodes(node => node.nativeNode === prevNode);
if (matches.length === 0) {

@@ -42,5 +51,12 @@ return undefined;

},
findDirectiveOrFail: (debugNode, directive) => {
const result = exports.MockHelper.findDirective(debugNode, directive);
if (!result) {
throw new Error(`Cannot find a directive via MockHelper.findDirectiveOrFail`);
}
return result;
},
findDirective: (debugNode, directive) => {
const result = [];
nestedCheck(result, debugNode, (node) => {
nestedCheck(result, debugNode, node => {
try {

@@ -57,3 +73,3 @@ return node.injector.get(directive);

const result = [];
nestedCheck(result, debugNode, (node) => {
nestedCheck(result, debugNode, node => {
try {

@@ -67,4 +83,20 @@ return node.injector.get(directive);

return result;
}
},
findOrFail: (el, sel) => {
const result = exports.MockHelper.find(el, sel);
if (!result) {
throw new Error(`Cannot find an element via MockHelper.findOrFail`);
}
return result;
},
find: (el, sel) => {
const term = typeof sel === 'string' ? platform_browser_1.By.css(sel) : platform_browser_1.By.directive(sel);
return el.query(term);
},
findAll: (el, sel) => {
const term = typeof sel === 'string' ? platform_browser_1.By.css(sel) : platform_browser_1.By.directive(sel);
return el.queryAll(term);
},
mockService: (instance, name, style) => mock_service_1.mockServiceHelper.mock(instance, name, style),
};
//# sourceMappingURL=mock-helper.js.map
import { ModuleWithProviders, Type } from '@angular/core';
import { Mock } from 'ng-mocks';
import { Mock } from '../common';
export declare type MockedModule<T> = T & Mock & {};
export declare function MockModule<T>(module: Type<T>): Type<MockedModule<T>>;
export declare function MockModule(module: ModuleWithProviders): ModuleWithProviders;

@@ -11,4 +11,6 @@ "use strict";

const core_1 = require("@angular/core");
const ng_mocks_1 = require("ng-mocks");
const common_2 = require("../common");
const reflect_1 = require("../common/reflect");
const mock_declaration_1 = require("../mock-declaration");
const mock_service_1 = require("../mock-service");
const cache = new Map();

@@ -30,8 +32,8 @@ const neverMockProvidedToken = [

const multi = typeof provider === 'object' && provider.multi;
if (typeof provide === 'object' && provide.ngMetadataName === 'InjectionToken'
&& neverMockProvidedToken.includes(provide.toString())) {
if (typeof provide === 'object' &&
provide.ngMetadataName === 'InjectionToken' &&
neverMockProvidedToken.includes(provide.toString())) {
return provider;
}
if (typeof provide === 'function'
&& neverMockProvidedFunction.includes(provide.name)) {
if (typeof provide === 'function' && neverMockProvidedFunction.includes(provide.name)) {
return provider;

@@ -42,3 +44,3 @@ }

provide,
useValue: ng_mocks_1.MockService(provide),
useValue: mock_service_1.MockService(provide),
};

@@ -57,7 +59,6 @@ };

const annotations = reflect_1.jitReflector.annotations(object);
const ngMetadataNames = annotations.map((annotation) => annotation.__proto__.ngMetadataName);
const ngMetadataNames = annotations.map(annotation => annotation.__proto__.ngMetadataName);
return ngMetadataNames.indexOf('NgModule') !== -1;
};
const isModuleWithProviders = (object) => typeof object.ngModule !== 'undefined'
&& isModule(object.ngModule);
const isModuleWithProviders = (object) => typeof object.ngModule !== 'undefined' && isModule(object.ngModule);
function MockModule(module) {

@@ -84,7 +85,7 @@ let ngModule;

else {
let ModuleMock = class ModuleMock extends ng_mocks_1.Mock {
let ModuleMock = class ModuleMock extends common_2.Mock {
};
ModuleMock = __decorate([
core_1.NgModule(MockIt(ngModule)),
ng_mocks_1.MockOf(ngModule)
common_2.MockOf(ngModule)
], ModuleMock);

@@ -97,4 +98,5 @@ moduleMockPointer = ModuleMock;

ngModule: moduleMockPointer,
providers: flatten(ngModuleProviders).map(mockProvider)
.filter((provider) => !!provider),
providers: flatten(ngModuleProviders)
.map(mockProvider)
.filter(provider => !!provider),
};

@@ -117,14 +119,15 @@ }

}
return ng_mocks_1.MockDeclaration(instance);
return mock_declaration_1.MockDeclaration(instance);
});
}
if (declarations.length) {
mockedModule.declarations = flatten(declarations).map(ng_mocks_1.MockDeclaration);
mockedModule.declarations = flatten(declarations).map(mock_declaration_1.MockDeclaration);
}
if (entryComponents.length) {
mockedModule.entryComponents = flatten(entryComponents).map(ng_mocks_1.MockDeclaration);
mockedModule.entryComponents = flatten(entryComponents).map(mock_declaration_1.MockDeclaration);
}
if (providers.length) {
mockedModule.providers = flatten(providers).map(mockProvider)
.filter((provider) => !!provider);
mockedModule.providers = flatten(providers)
.map(mockProvider)
.filter(provider => !!provider);
}

@@ -134,3 +137,4 @@ if (mockedModule.declarations || mockedModule.imports) {

if (mockedModule.imports) {
const onlyModules = mockedModule.imports.map((instance) => {
const onlyModules = mockedModule.imports
.map(instance => {
if (isModule(instance)) {

@@ -143,3 +147,4 @@ return instance;

return undefined;
}).filter((instance) => instance);
})
.filter(instance => instance);
mockedModule.exports = [...mockedModule.exports, ...onlyModules];

@@ -146,0 +151,0 @@ }

@@ -13,3 +13,3 @@ "use strict";

function MockPipes(...pipes) {
return pipes.map((pipe) => MockPipe(pipe, undefined));
return pipes.map(pipe => MockPipe(pipe, undefined));
}

@@ -16,0 +16,0 @@ exports.MockPipes = MockPipes;

@@ -1,6 +0,22 @@

import { Type } from '@angular/core';
import { DebugElement, Provider, Type } from '@angular/core';
import { ComponentFixture } from '@angular/core/testing';
export declare type DebugElementField = 'attributes' | 'childNodes' | 'children' | 'classes' | 'context' | 'injector' | 'listeners' | 'name' | 'nativeElement' | 'nativeNode' | 'parent' | 'properties' | 'providerTokens' | 'query' | 'queryAll' | 'queryAllNodes' | 'references' | 'styles' | 'triggerEventHandler';
export declare type MockedDebugElement<T> = {
componentInstance: T;
} & Pick<DebugElement, DebugElementField>;
export interface IMockRenderOptions {
detectChanges?: boolean;
providers?: Provider[];
}
export interface MockedComponentFixture<C = any, F = undefined> extends ComponentFixture<F> {
point: MockedDebugElement<C>;
}
declare function MockRender<MComponent, TComponent extends {
[key: string]: any;
}>(template: string | Type<MComponent>, params?: TComponent, detectChanges?: boolean): ComponentFixture<TComponent>;
}>(template: Type<MComponent>, params: TComponent, detectChanges?: boolean | IMockRenderOptions): MockedComponentFixture<MComponent, TComponent>;
declare function MockRender<MComponent>(template: Type<MComponent>): MockedComponentFixture<MComponent>;
declare function MockRender<MComponent, TComponent extends {
[key: string]: any;
}>(template: string, params: TComponent, detectChanges?: boolean | IMockRenderOptions): MockedComponentFixture<any, TComponent>;
declare function MockRender<MComponent>(template: string): MockedComponentFixture;
export { MockRender };

@@ -6,3 +6,4 @@ "use strict";

const reflect_1 = require("../common/reflect");
function MockRender(template, params, detectChanges = true) {
function MockRender(template, params, flags = true) {
const flagsObject = typeof flags === 'boolean' ? { detectChanges: flags } : flags;
let mockedTemplate = '';

@@ -40,2 +41,3 @@ if (typeof template === 'string') {

const options = {
providers: flagsObject.providers,
selector: 'mock-render',

@@ -55,5 +57,6 @@ template: mockedTemplate,

const fixture = testing_1.TestBed.createComponent(component);
if (detectChanges) {
if (flagsObject.detectChanges) {
fixture.detectChanges();
}
fixture.point = fixture.debugElement.children[0];
return fixture;

@@ -60,0 +63,0 @@ }

export declare type MockedFunction = () => undefined;
export declare const mockServiceHelper: {
mockFunction: (object?: {} | undefined, method?: string | undefined) => MockedFunction;
createMockFromPrototype: (service: any) => {
[key: string]: MockedFunction;
};
extractMethodsFromPrototype: (service: any) => string[];
extractMethodsFromPrototype(service: any): Array<keyof any>;
mock<T = MockedFunction>(instance: any, name: string, style?: 'get' | 'set'): T;
mockFunction(): MockedFunction;
registerMockFunction(mockFunction: (mockName: string) => MockedFunction | undefined): void;
};
export declare function MockService(service: boolean | number | string | null | undefined): undefined;
export declare function MockService<T extends {}>(service: T): any;
export declare function MockService(service?: boolean | number | string | null, mockNamePrefix?: string): undefined;
export declare function MockService<T extends {}>(service: T, mockNamePrefix?: string): any;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.mockServiceHelper = {
mockFunction: (object, method) => () => undefined,
const isFunc = (value) => {
if (typeof value !== 'function') {
return false;
}
const proto = value.toString();
if (proto.match(/^\(/) !== null) {
return true;
}
return proto.match(/^function\s*\(/) !== null;
};
const isClass = (value) => {
if (typeof value !== 'function') {
return false;
}
if (isFunc(value)) {
return false;
}
const proto = value.toString();
if (proto.match(/^class\b/) !== null) {
return true;
}
return proto.match(/^function\s*\(/) === null;
};
const isInst = (value) => {
if (value === null) {
return false;
}
if (typeof value !== 'object') {
return false;
}
if (value.ngMetadataName === 'InjectionToken') {
return false;
}
return typeof value.__proto__ === 'object';
};
let customMockFunction;
const mockServiceHelperPrototype = {
mockFunction: (mockName) => {
if (customMockFunction) {
return customMockFunction(mockName);
}
return () => undefined;
},
registerMockFunction: (mockFunction) => {
customMockFunction = mockFunction;
},
createMockFromPrototype: (service) => {
const methods = exports.mockServiceHelper.extractMethodsFromPrototype(service);
const methods = mockServiceHelperPrototype.extractMethodsFromPrototype(service);
const value = {};
for (const method of methods) {
value[method] = exports.mockServiceHelper.mockFunction(value, method);
if (value[method]) {
continue;
}
const mockName = `${service.constructor ? service.constructor.name : 'unknown'}.${method}`;
value[method] = mockServiceHelperPrototype.mockFunction(mockName);
}
if (typeof value === 'object') {
value.__proto__ = service;
}
return value;

@@ -23,5 +74,6 @@ },

const isGetterSetter = descriptor && (descriptor.get || descriptor.set);
if (!isGetterSetter && result.indexOf(method) === -1) {
result.push(method);
if (isGetterSetter || result.indexOf(method) !== -1) {
continue;
}
result.push(method);
}

@@ -31,11 +83,27 @@ prototype = Object.getPrototypeOf(prototype);

return result;
}
},
mock: (instance, name, style) => {
const def = Object.getOwnPropertyDescriptor(instance, name);
if (def && def[style || 'value']) {
return def[style || 'value'];
}
const mockName = `${typeof instance.prototype === 'function' ? instance.prototype.name : 'unknown'}.${name}${style ? `:${style}` : ''}`;
const mock = mockServiceHelperPrototype.mockFunction(mockName);
Object.defineProperty(instance, name, {
[style || 'value']: mock,
});
return mock;
},
};
function MockService(service) {
(window || global).ngMocksMockServiceHelper =
(window || global).ngMocksMockServiceHelper || mockServiceHelperPrototype;
const localHelper = (window || global).ngMocksMockServiceHelper;
exports.mockServiceHelper = (window || global).ngMocksMockServiceHelper;
function MockService(service, mockNamePrefix) {
let value;
if (typeof service === 'function' && service.prototype) {
value = exports.mockServiceHelper.createMockFromPrototype(service.prototype);
if (isClass(service)) {
value = localHelper.createMockFromPrototype(service.prototype);
}
else if (typeof service === 'function') {
value = exports.mockServiceHelper.mockFunction();
else if (isFunc(service)) {
value = localHelper.mockFunction(`func:${mockNamePrefix ? mockNamePrefix : service.name || 'arrow-function'}`);
}

@@ -45,8 +113,9 @@ else if (Array.isArray(service)) {

}
else if (typeof service === 'object' && service !== null && service.ngMetadataName !== 'InjectionToken') {
value = typeof service.constructor === 'function' && service.constructor.prototype
? exports.mockServiceHelper.createMockFromPrototype(service.constructor.prototype)
: {};
else if (isInst(service)) {
value =
typeof service.constructor === 'function'
? localHelper.createMockFromPrototype(service.constructor.prototype)
: {};
for (const property of Object.keys(service)) {
const mock = MockService(service[property]);
const mock = MockService(service[property], `${mockNamePrefix ? mockNamePrefix : 'instance'}.${property}`);
if (mock !== undefined) {

@@ -56,2 +125,3 @@ value[property] = mock;

}
value.__proto__ = service.__proto__;
}

@@ -58,0 +128,0 @@ return value;

{
"name": "ng-mocks",
"version": "9.2.0",
"version": "9.3.0",
"description": "Functions for creating angular mocks",

@@ -14,11 +14,15 @@ "main": "dist/index.js",

"scripts": {
"build": "npm run clean && tsc",
"build:all": "npm run lint && npm run test && npm run build",
"clean": "rm -rf dist coverage",
"commit": "npx git-cz",
"lint": "tslint --project tsconfig.json",
"build": "npm run clean && tsc",
"build:all": "npm run lint && npm run test && npm run build",
"lint:fix": "tslint --project tsconfig.json --fix",
"prettier:repo": "prettier --write \"**/*.*\"",
"prettier:stage": "pretty-quick --staged",
"release": "npm run lint && npm run test && npm run build && standard-version",
"test": "karma start",
"test:watch": "karma start --auto-watch --single-run=false",
"test:angular-versions": "sh build-with-supported-angluars.sh",
"test:debug": "npm run test:watch -- --browsers=Chrome",
"test:angular-versions": "sh build-with-supported-angluars.sh"
"test:watch": "karma start --auto-watch --single-run=false"
},

@@ -58,2 +62,4 @@ "repository": {

"@angular/router": "9.x",
"@commitlint/cli": "^8.3.5",
"@commitlint/config-conventional": "^8.3.4",
"@types/core-js": "^0.9.43",

@@ -63,2 +69,4 @@ "@types/jasmine": "^2.5.53",

"core-js": "^2.5.1",
"cz-conventional-changelog": "^3.1.0",
"husky": "^4.2.3",
"jasmine-ts": "^0.2.1",

@@ -71,2 +79,4 @@ "karma": "^3.1.3",

"karma-typescript": "^4.0.0",
"prettier": "^2.0.2",
"pretty-quick": "^2.0.1",
"puppeteer": "^2.1.1",

@@ -76,7 +86,12 @@ "rxjs": "^6.5.3",

"tslib": "^1.10.0",
"tslint": "^5.11.0",
"tslint-jasmine-rules": "^1.5.1",
"tslint": "^6.1.0",
"tslint-jasmine-rules": "^1.6.0",
"typescript": "3.6.4",
"zone.js": "^0.10.2"
},
"config": {
"commitizen": {
"path": "./node_modules/cz-conventional-changelog"
}
}
}

@@ -5,7 +5,10 @@ [![Build Status](https://travis-ci.org/ike18t/ng-mocks.png?branch=master)](https://travis-ci.org/ike18t/ng-mocks)

# ngMocks
Helper function for creating angular mocks for test.
## Why use this?
Sure, you could flip a flag on schema errors to make your component dependencies not matter. Or you could use this to mock them out and have the ability to assert on their inputs or emit on an output to assert on a side effect.
Sure, you could flip a flag on schema errors to make your component dependencies not matter.
Or you could use this to mock them out and have the ability to assert on their inputs or emit on an output to assert on a side effect.
## MockComponent(s)

@@ -17,11 +20,11 @@

- Mocked component templates are `ng-content` tags to allow transclusion
- When `@ContentChild` is present, then all of them will be wrapped as `[data-key="_id_"]`
and `ng-content` with `[data-key="ng-content"]`
- Supports `@ContentChild` with \$implicit context.
- Allows ng-model binding (You will have to add FormsModule to TestBed imports)
- Mocks Reactive Forms (You will have to add ReactiveFormsModule to TestBed imports)
- __simulateChange - calls `onChanged` on the mocked component bound to a FormControl
- __simulateTouch - calls `onTouched` on the mocked component bound to a FormControl
- \_\_simulateChange - calls `onChanged` on the mocked component bound to a FormControl
- \_\_simulateTouch - calls `onTouched` on the mocked component bound to a FormControl
- exportAs support
### Usage Example
```typescript

@@ -40,6 +43,3 @@ import { ComponentFixture, TestBed } from '@angular/core/testing';

TestBed.configureTestingModule({
declarations: [
TestedComponent,
MockComponent(DependencyComponent),
]
declarations: [TestedComponent, MockComponent(DependencyComponent)],
});

@@ -53,4 +53,3 @@

it('should send the correct value to the dependency component input', () => {
const mockedComponent = fixture.debugElement
.query(By.css('dependency-component-selector'))
const mockedComponent = fixture.debugElement.query(By.css('dependency-component-selector'))
.componentInstance as DependencyComponent; // casting to retain type safety

@@ -69,4 +68,3 @@

spyOn(component, 'trigger');
const mockedComponent = fixture.debugElement
.query(By.directive(DependencyComponent))
const mockedComponent = fixture.debugElement.query(By.directive(DependencyComponent))
.componentInstance as DependencyComponent; // casting to retain type safety

@@ -95,5 +93,3 @@

// assert on some side effect
const mockedNgContent = localFixture.debugElement
.query(By.directive(DependencyComponent))
.nativeElement.innerHTML;
const mockedNgContent = localFixture.debugElement.query(By.directive(DependencyComponent)).nativeElement.innerHTML;
expect(mockedNgContent).toContain('<p>inside content</p>');

@@ -111,5 +107,3 @@ });

// injected ng-content says as it was.
const mockedNgContent = localFixture.debugElement
.query(By.directive(DependencyComponent))
.nativeElement.innerHTML;
const mockedNgContent = localFixture.debugElement.query(By.directive(DependencyComponent)).nativeElement.innerHTML;
expect(mockedNgContent).toContain('<p>inside content</p>');

@@ -123,4 +117,3 @@

const mockedNgTemplate = mockedElement.query(By.css('[data-key="something"]'))
.nativeElement.innerHTML;
const mockedNgTemplate = mockedElement.query(By.css('[data-key="something"]')).nativeElement.innerHTML;
expect(mockedNgTemplate).toContain('<p>inside template</p>');

@@ -133,8 +126,9 @@ });

* Mocked directive with the same selector
* Inputs and Outputs with alias support
* Each directive instance has its own EventEmitter instances for outputs
* exportAs support
- Mocked directive with the same selector
- Inputs and Outputs with alias support
- Each directive instance has its own EventEmitter instances for outputs
- exportAs support
### Usage Example of Attribute Directives
```typescript

@@ -153,6 +147,3 @@ import { ComponentFixture, TestBed } from '@angular/core/testing';

TestBed.configureTestingModule({
declarations: [
TestedComponent,
MockDirective(DependencyDirective),
]
declarations: [TestedComponent, MockDirective(DependencyDirective)],
});

@@ -173,3 +164,3 @@

fixture.debugElement.query(By.css('span')),
DependencyDirective,
DependencyDirective
);

@@ -191,3 +182,3 @@ expect(mockedDirectiveInstance).toBeTruthy();

fixture.debugElement.query(By.css('span')),
DependencyDirective,
DependencyDirective
);

@@ -204,5 +195,8 @@ expect(mockedDirectiveInstance).toBeTruthy();

```
### Usage Example of Structural Directives
It's important to render a structural directive first with right context,
when assertions should be done on its nested elements.
```typescript

@@ -220,6 +214,3 @@ import { ComponentFixture, TestBed } from '@angular/core/testing';

TestBed.configureTestingModule({
declarations: [
TestedComponent,
MockDirective(DependencyDirective),
]
declarations: [TestedComponent, MockDirective(DependencyDirective)],
});

@@ -240,3 +231,4 @@

const mockedDirectiveInstance = MockHelper.findDirective(
fixture.debugElement, DependencyDirective
fixture.debugElement,
DependencyDirective
) as MockedDirective<DependencyDirective>;

@@ -261,7 +253,8 @@

```
## MockPipe(s)
* Mocked pipe with the same name.
* Ability to override the transform function with a type-safe function
* Default transform is () => undefined to prevent problems with chaining
- Mocked pipe with the same name.
- Ability to override the transform function with a type-safe function
- Default transform is () => undefined to prevent problems with chaining

@@ -271,2 +264,3 @@ Personally, I found the best thing to do for assertions is to override the transform to write the args so that I can assert on the arguments.

### Usage Example
```typescript

@@ -289,3 +283,3 @@ import { ComponentFixture, TestBed } from '@angular/core/testing';

MockPipe(DependencyPipe, (...args) => JSON.stringify(args)),
]
],
});

@@ -307,7 +301,8 @@

- Set value on the formControl by calling __simulateChange
- Set touched on the formControl by calling __simulateTouch
- Set value on the formControl by calling \_\_simulateChange
- Set touched on the formControl by calling \_\_simulateTouch
- Use the `MockedComponent` type to stay typesafe: `MockedComponent<YourReactiveFormComponent>`
### Usage Example
```typescript

@@ -327,9 +322,4 @@ import { ComponentFixture, TestBed } from '@angular/core/testing';

TestBed.configureTestingModule({
declarations: [
TestedComponent,
MockComponent(DependencyComponent),
],
imports: [
ReactiveFormsModule,
],
declarations: [TestedComponent, MockComponent(DependencyComponent)],
imports: [ReactiveFormsModule],
});

@@ -343,4 +333,3 @@

it('should send the correct value to the dependency component input', () => {
const mockedReactiveFormComponent = fixture.debugElement
.query(By.css('dependency-component-selector'))
const mockedReactiveFormComponent = fixture.debugElement.query(By.css('dependency-component-selector'))
.componentInstance as MockedComponent<DependencyComponent>; // casting to retain type safety

@@ -355,12 +344,15 @@

## MockDeclaration(s)
It figures out if it is a component, directive, or pipe and mocks it for you
## MockModule
* Mocks all components, directives, and pipes using MockDeclaration
* Providers are all mocked as empty objects
* Module Dependencies are also mocked
- Mocks all components, directives, and pipes using MockDeclaration
- Providers are all mocked as empty objects
- Module Dependencies are also mocked
For providers I typically will use TestBed.get(SomeProvider) and extend it using a library like [ts-mocks](https://www.npmjs.com/package/ts-mocks).
### Usage Example
```typescript

@@ -378,8 +370,4 @@ import { ComponentFixture, TestBed } from '@angular/core/testing';

TestBed.configureTestingModule({
declarations: [
TestedComponent,
],
imports: [
MockModule(DependencyModule),
],
declarations: [TestedComponent],
imports: [MockModule(DependencyModule)],
});

@@ -399,5 +387,18 @@

## MockRender
Providers simple way to render anything, change `@Inputs` and `@Outputs` of testing component, directives etc.
Provides a simple way to render anything for ease of testing directives, pipes, `@Inputs`, `@Outputs`, `@ContentChild` of a component, etc.
It returns a `fixture` of type `MockedComponentFixture` (it extends `ComponentFixture`) with a `point` property.
`fixture.componentInstance` belongs to the middle component for the render, that is quite useless,
when `fixture.point` points to the debugElement of the passed component.
Its type: `let fixture: MockedComponentFixture<ComponentToRender> = MockRender(ComponentToRender)`.
The best thing here is that `fixture.point.componentInstance` is typed to the component's class instead of any.
If you want you can specify providers for the render passing them via the 3rd parameter.
It is useful if you want to mock system tokens / services such as APP_INITIALIZER, DOCUMENT etc.
### Usage Example
```typescript

@@ -412,11 +413,6 @@ import { TestBed } from '@angular/core/testing';

describe('MockRender', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
TestedComponent,
],
imports: [
MockModule(DependencyModule),
],
declarations: [TestedComponent],
imports: [MockModule(DependencyModule)],
});

@@ -462,4 +458,3 @@ });

// assert on some side effect
const componentInstance = fixture.debugElement.query(By.directive(TestedComponent))
.componentInstance as TestedComponent;
const componentInstance = fixture.point.componentInstance; // it is not any, it is TestedComponent.
componentInstance.trigger.emit('foo2');

@@ -474,14 +469,110 @@ expect(componentInstance.value1).toEqual('something2');

## MockHelper
MockHelper provides 3 methods to get attribute and structural directives from an element.
`MockHelper.getDirective(fixture.debugElement, Directive)` -
returns attribute or structural directive which belongs to current element.
MockHelper provides functions to get attribute and structural directives from an element, find components and mock objects.
`MockHelper.findDirective(fixture.debugElement, Directive)` -
returns first found attribute or structural directive which belongs to current element or any child.
- getDirective
- getDirectiveOrFail
- findDirective
- findDirectiveOrFail
- findDirectives
`MockHelper.findDirectives(fixture.debugElement, Directive)`
returns all found attribute or structural directives which belong to current element and all its child.
* find
* findOrFail
* findAll
- mockService
```typescript
// returns attribute or structural directive
// which belongs to current element.
const directive: Directive | undefined = MockHelper.getDirective(fixture.debugElement, Directive);
// returns the first found attribute or structural directive
// which belongs to current element or any child.
const directive: Directive | undefined = MockHelper.findDirective(fixture.debugElement, Directive);
// returns an array of all found attribute or structural directives
// which belong to current element and all its child.
const directives: Array<Directive> = MockHelper.findDirectives(fixture.debugElement, Directive);
// returns a found DebugElement which belongs to the Component
// with the correctly typed componentInstance or null.
const component: MockedDebugElement<Component> | undefined = MockHelper.find(fixture.debugElement, Component);
// returns an array of found DebugElements which belong to the Component
// with the correctly typed componentInstance.
const components: Array<MockedDebugElement<Component>> = MockHelper.findAll(fixture.debugElement, Component);
// returns a found DebugElement which belongs to a css selector.
const component: MockedDebugElement<Component> | undefined = MockHelper.find(fixture.debugElement, 'div.container');
// returns an array of found DebugElements which belong to a css selector.
const components: Array<MockedDebugElement<Component>> = MockHelper.findAll(fixture.debugElement, 'div.item');
```
```typescript
// throws an error if the desired element wasn't found.
const directive: Directive = MockHelper.getDirectiveOrFail(fixture.debugElement, Directive);
const directive: Directive = MockHelper.findDirectiveOrFail(fixture.debugElement, Directive);
const component: MockedDebugElement<Component> = MockHelper.findOrFail(fixture.debugElement, Component);
const component: MockedDebugElement<Component> = MockHelper.findOrFail(fixture.debugElement, 'div.container');
```
In case if we want to mock methods / properties of a service / provider.
```typescript
// returns a mocked function / spy of the method. If the method hasn't been mocked yet - mocks it.
const spy: Spy = MockHelper.mockService(instance, methodName);
// returns a mocked function / spy of the property. If the property hasn't been mocked yet - mocks it.
const spyGet: Spy = MockHelper.mockService(instance, propertyName, 'get');
const spySet: Spy = MockHelper.mockService(instance, propertyName, 'set');
```
```typescript
// The example below uses auto spy.
it('mocks getters, setters and methods in a way that jasmine can mock them w/o an issue', () => {
const mock: GetterSetterMethodHuetod = MockService(GetterSetterMethodHuetod);
expect(mock).toBeDefined();
// Creating a mock on the getter.
MockHelper.mockService<Spy>(mock, 'name', 'get').and.returnValue('mock');
expect(mock.name).toEqual('mock');
// Creating a mock on the setter.
MockHelper.mockService(mock, 'name', 'set');
mock.name = 'mock';
expect(MockHelper.mockService(mock, 'name', 'set')).toHaveBeenCalledWith('mock');
// Creating a mock on the method.
MockHelper.mockService<Spy>(mock, 'nameMethod').and.returnValue('mock');
expect(mock.nameMethod('mock')).toEqual('mock');
expect(MockHelper.mockService(mock, 'nameMethod')).toHaveBeenCalledWith('mock');
// Creating a mock on the method that doesn't exist.
MockHelper.mockService<Spy>(mock, 'fakeMethod').and.returnValue('mock');
expect((mock as any).fakeMethod('mock')).toEqual('mock');
expect(MockHelper.mockService(mock, 'fakeMethod')).toHaveBeenCalledWith('mock');
});
```
## Auto Spy
Add the next code to `src/test.ts` if you want all mocked methods and functions to be a jasmine spy.
```typescript
import 'ng-mocks/dist/jasmine';
// uncomment in case if existing tests are with spies already.
// jasmine.getEnv().allowRespy(true);
```
In case of jest.
```typescript
import 'ng-mocks/dist/jest';
```
## Other examples of tests
More detailed examples can be found in

@@ -494,4 +585,5 @@ [e2e](https://github.com/ike18t/ng-mocks/tree/master/e2e)

## Find an issue or have a request?
Report it as an issue or submit a PR. I'm open to contributions.
Report it as an issue or submit a PR. I'm open to contributions.
<https://github.com/ike18t/ng-mocks>

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc