Best JavaScript code snippet using ng-mocks
mock-module.ts
Source:mock-module.ts
1import { NgModule, Provider } from '@angular/core';2import coreConfig from '../common/core.config';3import { extendClass } from '../common/core.helpers';4import coreReflectModuleResolve from '../common/core.reflect.module-resolve';5import { AnyType, Type } from '../common/core.types';6import decorateMock from '../common/decorate.mock';7import funcGetName from '../common/func.get-name';8import funcImportExists from '../common/func.import-exists';9import { isMockNgDef } from '../common/func.is-mock-ng-def';10import { isNgDef } from '../common/func.is-ng-def';11import { isNgModuleDefWithProviders, NgModuleWithProviders } from '../common/func.is-ng-module-def-with-providers';12import { Mock } from '../common/mock';13import ngMocksUniverse from '../common/ng-mocks-universe';14import mockNgDef from './mock-ng-def';15const flagMock = (resolution?: string): boolean => resolution === 'mock' && ngMocksUniverse.flags.has('skipMock');16const flagKeep = (resolution?: string): boolean => resolution === 'keep' && !ngMocksUniverse.flags.has('skipMock');17const flagReplace = (resolution?: string): boolean =>18 resolution === 'replace' && !ngMocksUniverse.flags.has('skipMock');19const flagNever = (ngModule?: any): boolean =>20 coreConfig.neverMockModule.indexOf(funcGetName(ngModule)) !== -1 && !ngMocksUniverse.flags.has('skipMock');21const preProcessFlags = (ngModule: AnyType<any>): { isRootModule: boolean; toggleSkipMockFlag: boolean } => {22 let toggleSkipMockFlag = false;23 let isRootModule = true;24 if (ngMocksUniverse.flags.has('hasRootModule')) {25 isRootModule = false;26 } else {27 ngMocksUniverse.flags.add('hasRootModule');28 }29 const resolution = ngMocksUniverse.getResolution(ngModule);30 if (flagMock(resolution)) {31 toggleSkipMockFlag = true;32 ngMocksUniverse.flags.delete('skipMock');33 }34 if (flagNever(ngModule)) {35 toggleSkipMockFlag = true;36 ngMocksUniverse.flags.add('skipMock');37 }38 if (!isRootModule && (flagKeep(resolution) || flagReplace(resolution))) {39 toggleSkipMockFlag = true;40 ngMocksUniverse.flags.add('skipMock');41 }42 return {43 isRootModule,44 toggleSkipMockFlag,45 };46};47const postProcessFlags = ({48 isRootModule,49 toggleSkipMockFlag,50}: {51 isRootModule: boolean;52 toggleSkipMockFlag: boolean;53}): void => {54 if (toggleSkipMockFlag && ngMocksUniverse.flags.has('skipMock')) {55 ngMocksUniverse.flags.delete('skipMock');56 } else if (toggleSkipMockFlag && !ngMocksUniverse.flags.has('skipMock')) {57 ngMocksUniverse.flags.add('skipMock');58 }59 if (isRootModule) {60 ngMocksUniverse.flags.delete('hasRootModule');61 }62};63const extractModuleAndProviders = (64 module: any,65): {66 ngModule: Type<any>;67 ngModuleProviders: Provider[] | undefined;68} => {69 let ngModule: Type<any>;70 let ngModuleProviders: Provider[] | undefined;71 if (isNgModuleDefWithProviders(module)) {72 ngModule = module.ngModule;73 if (module.providers) {74 ngModuleProviders = module.providers;75 }76 } else {77 ngModule = module;78 }79 return {80 ngModule,81 ngModuleProviders,82 };83};84const getExistingMockModule = (ngModule: Type<any>, isRootModule: boolean): Type<any> | undefined => {85 if (isMockNgDef(ngModule, 'm')) {86 return ngModule;87 }88 // Every module should be replaced with its mock copy only once to avoid errors like:89 // Failed: Type ...Component is part of the declarations of 2 modules: ...Module and ...Module...90 if (ngMocksUniverse.flags.has('cacheModule') && ngMocksUniverse.cacheDeclarations.has(ngModule)) {91 return ngMocksUniverse.cacheDeclarations.get(ngModule);92 }93 // Now we check if we need to keep the original module or to replace it with some other.94 // and there is no override in its resolution.95 if (isRootModule || ngMocksUniverse.config.get('ngMocksDepsResolution')?.get(ngModule) === 'mock') {96 return undefined;97 }98 if (ngMocksUniverse.hasBuildDeclaration(ngModule)) {99 const instance = ngMocksUniverse.getBuildDeclaration(ngModule);100 if (isNgDef(instance, 'm') && instance !== ngModule) {101 return instance;102 }103 }104 return undefined;105};106const getMockModuleDef = (ngModule: Type<any>, mockModule?: Type<any>): NgModule | undefined => {107 if (!mockModule) {108 const meta = coreReflectModuleResolve(ngModule);109 const [changed, ngModuleDef] = mockNgDef(meta, ngModule);110 if (changed) {111 return ngModuleDef;112 }113 }114 return undefined;115};116const detectMockModule = (ngModule: Type<any>, mockModule?: Type<any>): Type<any> => {117 const mockModuleDef = getMockModuleDef(ngModule, mockModule);118 if (mockModuleDef) {119 const parent = ngMocksUniverse.flags.has('skipMock') ? ngModule : Mock;120 const mock = extendClass(parent);121 // the last thing is to apply decorators.122 NgModule(mockModuleDef)(mock);123 decorateMock(mock, ngModule);124 return mock;125 }126 return mockModule || ngModule;127};128const getMockProviders = (ngModuleProviders: Provider[] | undefined): Provider[] | undefined => {129 if (ngModuleProviders) {130 const [changed, ngModuleDef] = mockNgDef({ providers: ngModuleProviders });131 return changed ? ngModuleDef.providers : ngModuleProviders;132 }133 return undefined;134};135const generateReturn = (136 module: any,137 ngModule: AnyType<any>,138 ngModuleProviders: Provider[] | undefined,139 mockModule: AnyType<any>,140 mockModuleProviders: Provider[] | undefined,141): any =>142 mockModule === ngModule && mockModuleProviders === ngModuleProviders143 ? module144 : isNgModuleDefWithProviders(module)145 ? { ngModule: mockModule, ...(mockModuleProviders ? { providers: mockModuleProviders } : {}) }146 : mockModule;147/**148 * MockModule creates a mock module class out of an arbitrary module.149 * All declarations, imports, exports and providers will be mocked too.150 *151 * @see https://ng-mocks.sudo.eu/api/MockModule152 *153 * ```ts154 * TestBed.configureTestingModule({155 * imports: [156 * MockModule(SharedModule),157 * ],158 * });159 * ```160 */161export function MockModule<T>(ngModule: Type<T>): Type<T>;162/**163 * MockModule creates a mock module class with mock provides out of an arbitrary module with providers.164 * All declarations, imports, exports and providers will be mocked too.165 *166 * @see https://ng-mocks.sudo.eu/api/MockModule167 *168 * ```ts169 * TestBed.configureTestingModule({170 * imports: [171 * MockModule(StoreModule.forRoot()),172 * ],173 * });174 * ```175 */176export function MockModule<T>(ngModule: NgModuleWithProviders<T>): NgModuleWithProviders<T>;177export function MockModule(def: any): any {178 funcImportExists(def, 'MockModule');179 const { ngModule, ngModuleProviders } = extractModuleAndProviders(def);180 const flags = preProcessFlags(ngModule);181 try {182 const mockModule = detectMockModule(ngModule, getExistingMockModule(ngModule, flags.isRootModule));183 // istanbul ignore else184 if (ngMocksUniverse.flags.has('cacheModule')) {185 ngMocksUniverse.cacheDeclarations.set(ngModule, mockModule);186 }187 if (ngMocksUniverse.flags.has('skipMock')) {188 ngMocksUniverse.config.get('ngMocksDepsSkip')?.add(mockModule);189 }190 const mockModuleProviders = getMockProviders(ngModuleProviders);191 return generateReturn(def, ngModule, ngModuleProviders, mockModule, mockModuleProviders);192 } finally {193 postProcessFlags(flags);194 }...
mock-ng-def.ts
Source:mock-ng-def.ts
1import { Component, Directive, NgModule, Pipe, Provider } from '@angular/core';2import { flatten } from '../common/core.helpers';3import { dependencyKeys, Type } from '../common/core.types';4import { isNgModuleDefWithProviders } from '../common/func.is-ng-module-def-with-providers';5import ngMocksUniverse from '../common/ng-mocks-universe';6import createResolvers from './create-resolvers';7import markProviders from './mark-providers';8const flatToExisting = <T, R>(data: T | T[], callback: (arg: T) => R | undefined): R[] =>9 flatten(data)10 .map(callback)11 .filter((item): item is R => !!item);12const configureProcessMetaKeys = (13 resolve: (def: any) => any,14 resolveProvider: (def: Provider) => any,15): Array<[dependencyKeys, (def: any) => any]> => [16 ['declarations', resolve],17 ['entryComponents', resolve],18 ['bootstrap', resolve],19 ['providers', resolveProvider],20 ['viewProviders', resolveProvider],21 ['imports', resolve],22 ['exports', resolve],23];24const processMeta = (25 ngModule: Partial<Record<dependencyKeys, any>> & {26 skipMarkProviders?: boolean;27 },28 resolve: (def: any) => any,29 resolveProvider: (def: Provider) => any,30): NgModule => {31 const mockModuleDef: Partial<NgModule & Component & Directive & Pipe> = {};32 const keys = configureProcessMetaKeys(resolve, resolveProvider);33 const cachePipe = ngMocksUniverse.flags.has('cachePipe');34 if (!cachePipe) {35 ngMocksUniverse.flags.add('cachePipe');36 }37 for (const [key, callback] of keys) {38 if (ngModule[key]?.length) {39 mockModuleDef[key] = flatToExisting(ngModule[key], callback);40 }41 }42 if (!ngModule.skipMarkProviders) {43 markProviders(mockModuleDef.providers);44 markProviders(mockModuleDef.viewProviders);45 }46 if (!cachePipe) {47 ngMocksUniverse.flags.delete('cachePipe');48 }49 return mockModuleDef;50};51const resolveDefForExport = (52 def: any,53 resolve: (def: any) => any,54 correctExports: boolean,55 ngModule?: Type<any>,56): Type<any> | undefined => {57 const moduleConfig = ngMocksUniverse.config.get(ngModule) || {};58 const instance = isNgModuleDefWithProviders(def) ? def.ngModule : def;59 const mockDef = resolve(instance);60 if (!mockDef) {61 return undefined;62 }63 // If we export a declaration, then we have to export its module too.64 const config = ngMocksUniverse.config.get(instance);65 if (config?.export && ngModule && !moduleConfig.export) {66 ngMocksUniverse.config.set(ngModule, {67 ...moduleConfig,68 export: true,69 });70 }71 if (correctExports && !moduleConfig.exportAll && !config?.export) {72 return undefined;73 }74 return mockDef;75};76const skipAddExports = (mockDef: any, mockModuleDef: NgModule): mockDef is undefined =>77 !mockDef || (!!mockModuleDef.exports && mockModuleDef.exports.indexOf(mockDef) !== -1);78// if we are in the skipMock mode we need to export only the default exports.79// if we are in the correctModuleExports mode we need to export only default exports.80const addExports = (81 resolve: (def: any) => any,82 change: () => void,83 ngModuleDef: NgModule,84 mockModuleDef: NgModule,85 ngModule?: Type<any>,86): void => {87 const correctExports = ngMocksUniverse.flags.has('skipMock') || ngMocksUniverse.flags.has('correctModuleExports');88 for (const def of flatten([ngModuleDef.imports || [], ngModuleDef.declarations || []])) {89 const mockDef = resolveDefForExport(def, resolve, correctExports, ngModule);90 if (skipAddExports(mockDef, mockModuleDef)) {91 continue;92 }93 change();94 mockModuleDef.exports = mockModuleDef.exports || [];95 mockModuleDef.exports.push(mockDef);96 }97};98export default (99 ngModuleDef: NgModule & {100 skipMarkProviders?: boolean;101 },102 ngModule?: Type<any>,103): [boolean, NgModule] => {104 const hasResolver = ngMocksUniverse.config.has('mockNgDefResolver');105 if (!hasResolver) {106 ngMocksUniverse.config.set('mockNgDefResolver', new Map());107 }108 let changed = !ngMocksUniverse.flags.has('skipMock');109 const change = (flag = true) => {110 changed = changed || flag;111 };112 const { resolve, resolveProvider } = createResolvers(change, ngMocksUniverse.config.get('mockNgDefResolver'));113 const mockModuleDef = processMeta(ngModuleDef, resolve, resolveProvider);114 addExports(resolve, change, ngModuleDef, mockModuleDef, ngModule);115 if (!hasResolver) {116 ngMocksUniverse.config.delete('mockNgDefResolver');117 }118 return [changed, mockModuleDef];...
Using AI Code Generation
1import { mockModuleDef } from 'ng-mocks';2import { AppModule } from './app.module';3describe('AppComponent', () => {4 let component: AppComponent;5 let fixture: ComponentFixture<AppComponent>;6 beforeEach(() => {7 const mockModule = mockModuleDef(AppModule, {8 imports: [RouterTestingModule],9 });10 TestBed.configureTestingModule(mockModule).compileComponents();11 });12 beforeEach(() => {13 fixture = TestBed.createComponent(AppComponent);14 component = fixture.componentInstance;15 fixture.detectChanges();16 });17 it('should create', () => {18 expect(component).toBeTruthy();19 });20});21Error: Uncaught (in promise): Error: No component factory found for AppComponent. Did you add it to @NgModule.entryComponents?22import { mockModuleDef } from 'ng-mocks';23import { AppModule } from './app.module';24describe('AppComponent', () => {25 let component: AppComponent;26 let fixture: ComponentFixture<AppComponent>;27 beforeEach(() => {28 const mockModule = mockModuleDef(AppModule, {29 imports: [RouterTestingModule],30 });31 TestBed.configureTestingModule(mockModule).compileComponents();32 });33 beforeEach(() => {34 fixture = TestBed.createComponent(AppComponent);35 component = fixture.componentInstance;36 fixture.detectChanges();37 });38 it('should create', () => {39 expect(component).toBeTruthy();40 });41});
Using AI Code Generation
1import { mockModuleDef } from 'ng-mocks';2const mockModule = mockModuleDef({3 imports: [HttpClientModule],4});5const mockComponent = mockComponentDef({6});7const mockComponent2 = mockComponentDef({8});9const mockComponent3 = mockComponentDef({10});11const mockComponent4 = mockComponentDef({12});13const mockComponent5 = mockComponentDef({14});
Using AI Code Generation
1import { mockModuleDef } from 'ng-mocks';2import { MyModule } from './my-module';3describe('MyModule', () => {4 beforeEach(() => {5 moduleDef = mockModuleDef(MyModule);6 });7 it('should have a component', () => {8 expect(moduleDef.declarations).toContain(MyComponent);9 });10 it('should have a directive', () => {11 expect(moduleDef.declarations).toContain(MyDirective);12 });13 it('should have a pipe', () => {14 expect(moduleDef.declarations).toContain(MyPipe);15 });16 it('should have a service', () => {17 expect(moduleDef.providers).toContain(MyService);18 });19});20import { mockModuleDef, setModuleDef } from 'ng-mocks';21import { MyModule } from './my-module';22describe('MyModule', () => {23 beforeEach(() => {24 moduleDef = mockModuleDef(MyModule);25 setModuleDef(MyModule, moduleDef);26 });27 it('should have a component', () => {28 expect(moduleDef.declarations).toContain(MyComponent);29 });30 it('should have a directive', () => {31 expect(moduleDef.declarations).toContain(MyDirective);32 });33 it('should have
Using AI Code Generation
1import { mockModuleDef } from 'ng-mocks';2const mockModule = mockModuleDef({3 imports: [4});5describe('test', () => {6 beforeEach(() => {7 TestBed.configureTestingModule(mockModule);8 });9});10Error: Unexpected value 'undefined' imported by the module 'DynamicTestModule'11Error: Unexpected value 'undefined' imported by the module 'DynamicTestModule'12import { mockModuleDef } from 'ng-mocks';13const mockModule = mockModuleDef({14 imports: [15 StoreModule.forRoot({}),16 EffectsModule.forRoot([]),17 { provide: Store, useClass: MockStore },18 { provide: Actions, useValue: new Subject() },19});20Error: Unexpected value 'undefined' imported by the module 'DynamicTestModule'21import { mockModuleDef } from 'ng-mocks';22const mockModule = mockModuleDef({23 imports: [24 StoreModule.forRoot({}),
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!