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 }...
Using AI Code Generation
1import { mockModuleProviders } from 'ng-mocks';2import { MyService } from './my.service';3import { MyComponent } from './my.component';4import { MyModule } from './my.module';5describe('MyComponent', () => {6 beforeEach(() => {7 mockModuleProviders(MyModule, [8 {9 useValue: {10 getFoo: () => {11 return 'bar';12 },13 },14 },15 ]);16 });17});18import { mockModuleProviders } from 'ng-mocks';19import { MyService } from './my.service';20import { MyComponent } from './my.component';21import { MyModule } from './my.module';22describe('MyComponent', () => {23 beforeEach(() => {24 mockModuleProviders(MyModule, [25 {26 useValue: {27 getFoo: () => {28 return 'bar';29 },30 },31 },32 ]);33 });34 it('should return bar', () => {35 const fixture = TestBed.createComponent(MyComponent);36 const component = fixture.componentInstance;37 expect(component.getFoo()).toBe('bar');38 });39 it('should return baz', () => {40 mockModuleProviders(MyModule, [41 {42 useValue: {43 getFoo: () => {44 return 'baz';45 },46 },47 },48 ]);49 const fixture = TestBed.createComponent(MyComponent);50 const component = fixture.componentInstance;51 expect(component.getFoo()).toBe('baz');52 });53 it('should return foo', () => {54 mockModuleProviders(MyModule, [55 {56 useValue: {57 getFoo: () => {58 return 'foo';59 },60 },61 },62 ]);
Using AI Code Generation
1import { mockModuleProviders } from 'ng-mocks';2import { MockComponent } from 'ng-mocks';3import { MockModule } from 'ng-mocks';4import { MockPipe } from 'ng-mocks';5import { MockRender } from 'ng-mocks';6import { MockService } from 'ng-mocks';7import { MockedComponentFixture, MockedDebugElement } from 'ng-mocks';8import { MockedDirective } from 'ng-mocks';9import { MockedPipe } from 'ng-mocks';10import { MockedProvider } from 'ng-mocks';11import { MockedRenderResult } from 'ng-mocks';12import { MockedService } from 'ng-mocks';13import { MockedStaticProvider } from 'ng-mocks';14import { MockedType } from 'ng-mocks';15import { MockedWithProviders } from 'ng-mocks';16import { MockProvider } from 'ng-mocks';17import { MockRenderOptions } from 'ng-mocks';18import { ngMocks } from 'ng-mocks';19import { ngMocksUniverse } from 'ng-mocks';20import { ngMocksUniverse as universe } from 'ng-mocks';21import { ngMocksUniverse } from 'ng-mocks';22import { ngMocksUniverse as universe } from 'ng-mocks';23import { ngMocksUniverse as universe } from 'ng-mocks';24import { ngMocksUniver
Using AI Code Generation
1import { mockModuleProviders } from 'ng-mocks';2import { MockModule } from 'ng-mocks';3import { MockProvider } from 'ng-mocks';4import { MockRender } from 'ng-mocks';5import { TestBed } from '@angular/core/testing';6import { Component } from '@angular/core';7import { Service1 } from './service1';8import { Service2 } from './service2';9@Component({10})11class TestComponent {}12describe('TestComponent', () => {13 beforeEach(() => {14 TestBed.configureTestingModule({15 providers: mockModuleProviders(TestComponent, {16 })17 });18 });19 it('should create', () => {20 const fixture = MockRender(TestComponent);21 expect(fixture.point.componentInstance).toBeTruthy();22 });23});24import { Injectable } from '@angular/core';25@Injectable({26})27export class Service1 {28 constructor() {}29}30import { Injectable } from '@angular/core';31@Injectable({32})33export class Service2 {34 constructor() {}35}36import { Injectable } from '@angular/core';37@Injectable({38})39export class Service3 {40 constructor() {}41}42import { Injectable } from '@angular/core';43@Injectable({44})45export class Service4 {46 constructor() {}47}48import { Injectable } from '@angular/core';49@Injectable({50})51export class Service5 {52 constructor() {}53}54import { Injectable } from '@angular/core';55@Injectable({56})57export class Service6 {58 constructor() {}59}60import { Injectable } from '@angular/core';61@Injectable({62})63export class Service7 {64 constructor() {}65}66import { Injectable } from '@angular/core';67@Injectable({68})69export class Service8 {70 constructor() {}71}72import { Injectable } from '@angular/core';73@Injectable({74})75export class Service9 {76 constructor() {}77}
Using AI Code Generation
1import { mockModuleProviders } from 'ng-mocks';2import { MockModule } from 'ng-mocks';3import { MockPipe } from 'ng-mocks';4import { Pipe, PipeTransform } from '@angular/core';5import { TestBed } from '@angular/core/testing';6import { TestModule } from './test.module';7import { TestComponent } from './test.component';8describe('TestComponent', () => {9 let component: TestComponent;10 beforeEach(() => {11 TestBed.configureTestingModule({12 MockPipe(TestPipe, () => 'mocked'),13 imports: [14 MockModule(TestModule),15 });16 component = TestBed.createComponent(TestComponent).componentInstance;17 });18 it('should work', () => {19 expect(component).toBeDefined();20 });21});22import { NgModule } from '@angular/core';23import { CommonModule } from '@angular/common';24import { TestComponent } from './test.component';25import { TestPipe } from './test.pipe';26@NgModule({27 imports: [CommonModule],28})29export class TestModule {}30import { Component } from '@angular/core';31import { TestPipe } from './test.pipe';32@Component({33 {{ 'test' | test }}34})35export class TestComponent {}36import { Pipe, PipeTransform } from '@angular/core';37@Pipe({38})39export class TestPipe implements PipeTransform {40 transform(value: unknown): unknown {41 return value;42 }43}44import { mockModuleProviders } from 'ng-mocks';45import { MockModule } from 'ng-mocks';46import { MockPipe } from 'ng-mocks';47import { Pipe, PipeTransform } from '@angular/core';48import { TestBed } from '@angular/core/testing';49import { TestModule } from './test.module';50import { TestComponent } from './test.component';51describe('TestComponent', () => {52 let component: TestComponent;53 beforeEach(() => {54 TestBed.configureTestingModule({55 MockPipe(TestPipe, () => 'mocked'),56 imports: [57 MockModule(TestModule),58 });
Using AI Code Generation
1import { mockModuleProviders } from 'ng-mocks';2import { MockModule } from 'ng-mocks';3import { AppModule } from './app.module';4import { AppComponent } from './app.component';5import { AppModule } from './app.module';6import { AppComponent } from './app.component';7import { ComponentFixture, TestBed } from '@angular/core/testing';8import { By } from '@angular/platform-browser';9describe('AppComponent', () => {10 let component: AppComponent;11 let fixture: ComponentFixture<AppComponent>;12 beforeEach(async () => {13 await TestBed.configureTestingModule({14 imports: [MockModule(AppModule)],15 providers: mockModuleProviders(AppModule),16 }).compileComponents();17 });18 beforeEach(() => {19 fixture = TestBed.createComponent(AppComponent);20 component = fixture.componentInstance;21 fixture.detectChanges();22 });23 it('should create', () => {24 expect(component).toBeTruthy();25 });26 it('should have a title', () => {27 const title = fixture.debugElement.query(By.css('h1')).nativeElement;28 expect(title.textContent).toContain('My First Angular App');29 });30});31import { NgModule } from '@angular/core';32import { BrowserModule } from '@angular/platform-browser';33import { AppComponent } from './app.component';34import { AppRoutingModule } from './app-routing.module';35import { AboutComponent } from './about/about.component';36import { HomeComponent } from './home/home.component';37import { HttpClientModule } from '@angular/common/http';38@NgModule({39 imports: [BrowserModule, AppRoutingModule, HttpClientModule],40})41export class AppModule {}42import { Component } from '@angular/core';43@Component({44})45export class AppComponent {46 title = 'My First Angular App';47}48<h1>{{ title }}</h1>49import { NgModule } from '@angular/core';50import { Routes, RouterModule } from '@angular/router';51import { AboutComponent } from './about/about.component';52import { HomeComponent } from './home/home.component';53 { path: '', component: HomeComponent },54 { path: 'about', component: AboutComponent },55];56@NgModule({57 imports: [RouterModule.forRoot(routes)],
Using AI Code Generation
1import { mockModuleProviders } from 'ng-mocks';2import { MockModule } from 'ng-mocks/dist/lib/mock-module';3import { SomeService } from './some.service';4import { SomeComponent } from './some.component';5describe('SomeComponent', () => {6 let component: SomeComponent;7 let fixture: ComponentFixture<SomeComponent>;8 beforeEach(async(() => {9 TestBed.configureTestingModule({10 imports: [MockModule(SomeService)]11 });12 mockModuleProviders(SomeService, { provide: SomeService, useValue: {} });13 }));14 beforeEach(() => {15 fixture = TestBed.createComponent(SomeComponent);16 component = fixture.componentInstance;17 fixture.detectChanges();18 });19 it('should create', () => {20 expect(component).toBeTruthy();21 });22});23import { Injectable } from '@angular/core';24@Injectable()25export class SomeService {26 public getSomeData() {27 return 'some data';28 }29}30import { Component, OnInit } from '@angular/core';31import { SomeService } from './some.service';32@Component({33})34export class SomeComponent implements OnInit {35 public someData: string;36 constructor(private someService: SomeService) {}37 ngOnInit() {38 this.someData = this.someService.getSomeData();39 }40}41{{ someData }}42import { TestBed, async, ComponentFixture } from '@angular/core/testing';43import { SomeComponent } from './some.component';44describe('SomeComponent', () => {45 let component: SomeComponent;46 let fixture: ComponentFixture<SomeComponent>;47 beforeEach(async(() => {48 TestBed.configureTestingModule({49 });50 }));51 beforeEach(() => {52 fixture = TestBed.createComponent(SomeComponent);53 component = fixture.componentInstance;54 fixture.detectChanges();55 });56 it('should create', () => {57 expect(component).toBeTruthy();58 });59});60import { TestBed } from '@angular/core/testing';61import { SomeService } from './some.service';62describe('SomeService', () => {63 beforeEach(() => TestBed.configureTestingModule({}));64 it('should be created', () => {
Using AI Code Generation
1import { mockModuleProviders } from 'ng-mocks';2import { TestModule } from './test.module';3import { TestService } from './test.service';4describe('Test', () => {5 mockModuleProviders(TestModule, [6 {7 useValue: {8 test: () => 'mocked test',9 },10 },11 ]);12 beforeEach(() => TestBed.configureTestingModule({ imports: [TestModule] }));13 it('should test', () => {14 const testService = TestBed.get(TestService);15 expect(testService.test()).toBe('mocked test');16 });17});18import { Injectable } from '@angular/core';19@Injectable()20export class TestService {21 test() {22 return 'test';23 }24}25import { NgModule } from '@angular/core';26import { TestService } from './test.service';27@NgModule({28})29export class TestModule {}30describe('Test', () => {31 it('should test', () => {32 expect('test').toBe('test');33 });34});35 at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)36 at Function.Module._load (internal/modules/cjs/loader.js:562:25)37 at Module.require (internal/modules/cjs/loader.js:692:17)38 at require (internal/modules/cjs/helpers.js:25:18)39 at Object.<anonymous> (/home/rajesh/Downloads/angular-mocks/src/test.js:1:76)40 at Module._compile (internal/modules/cjs/loader.js:778:30)41 at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)42 at Module.load (internal/modules/cjs/loader.js:653:32)43 at tryModuleLoad (internal/modules/cjs/loader.js:593:12)44 at Function.Module._load (internal/modules/cjs/loader.js:585:3)
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!!