Best JavaScript code snippet using ng-mocks
mock-builder.promise.ts
Source:mock-builder.promise.ts
1import { Provider } from '@angular/core';2import { TestBed, TestBedStatic, TestModuleMetadata } from '@angular/core/testing';3import { flatten, mapValues } from '../common/core.helpers';4import { Type } from '../common/core.types';5import funcGetName from '../common/func.get-name';6import { isNgDef } from '../common/func.is-ng-def';7import { isNgModuleDefWithProviders } from '../common/func.is-ng-module-def-with-providers';8import ngMocksUniverse from '../common/ng-mocks-universe';9import { MockBuilderStash } from './mock-builder-stash';10import addRequestedProviders from './promise/add-requested-providers';11import applyPlatformModules from './promise/apply-platform-modules';12import createNgMocksOverridesToken from './promise/create-ng-mocks-overrides-token';13import createNgMocksToken from './promise/create-ng-mocks-token';14import createNgMocksTouchesToken from './promise/create-ng-mocks-touches-token';15import handleEntryComponents from './promise/handle-entry-components';16import handleRootProviders from './promise/handle-root-providers';17import initNgModules from './promise/init-ng-modules';18import initUniverse from './promise/init-universe';19import parseMockArguments from './promise/parse-mock-arguments';20import parseProvider from './promise/parse-provider';21import { BuilderData } from './promise/types';22import { IMockBuilder, IMockBuilderConfig, IMockBuilderConfigAll, IMockBuilderResult } from './types';23const normaliseModule = (24 module: any,25): {26 def: Type<any>;27 providers?: Provider[];28} =>29 isNgModuleDefWithProviders(module)30 ? { def: module.ngModule, providers: module.providers }31 : { def: module, providers: undefined };32const generateProviderValue = (provider: any, existing: any, multi: boolean): any =>33 multi ? [...(Array.isArray(existing) ? existing : /* istanbul ignore next */ []), provider] : provider;34const defaultMock = {}; // simulating Symbol35export interface MockBuilderPromise {36 [Symbol.toStringTag]: 'Promise';37}38export class MockBuilderPromise implements IMockBuilder {39 protected beforeCC: Set<(testBed: TestBedStatic) => void> = new Set();40 protected configDef: BuilderData['configDef'] = new Map();41 protected defProviders: BuilderData['defProviders'] = new Map();42 protected defValue: BuilderData['defValue'] = new Map();43 protected excludeDef: BuilderData['excludeDef'] = new Set();44 protected keepDef: BuilderData['keepDef'] = new Set();45 protected mockDef: BuilderData['mockDef'] = new Set();46 protected providerDef: BuilderData['providerDef'] = new Map();47 protected replaceDef: BuilderData['replaceDef'] = new Set();48 protected stash: MockBuilderStash = new MockBuilderStash();49 public constructor(protected configDefault: IMockBuilderConfigAll) {50 // istanbul ignore else51 if (typeof Symbol !== 'undefined') {52 (this as any)[Symbol.toStringTag] = 'Promise';53 }54 }55 public beforeCompileComponents(callback: (testBed: TestBedStatic) => void): this {56 this.beforeCC.add(callback);57 return this;58 }59 public build(): TestModuleMetadata {60 this.stash.backup();61 ngMocksUniverse.config.set('mockNgDefResolver', new Map());62 ngMocksUniverse.flags.add('hasRootModule');63 try {64 const params = this.combineParams();65 const ngModule = initNgModules(params, initUniverse(params));66 addRequestedProviders(ngModule, params);67 handleRootProviders(ngModule, params);68 handleEntryComponents(ngModule);69 applyPlatformModules();70 ngModule.providers.push(71 createNgMocksToken(),72 createNgMocksTouchesToken(),73 createNgMocksOverridesToken(this.replaceDef, this.defValue),74 );75 return ngModule;76 } finally {77 ngMocksUniverse.flags.delete('hasRootModule');78 ngMocksUniverse.config.delete('mockNgDefResolver');79 this.stash.restore();80 }81 }82 // istanbul ignore next83 public async catch(reject?: ((reason: any) => PromiseLike<never>) | undefined | null): Promise<IMockBuilderResult> {84 return this.then().catch(reject);85 }86 public exclude(def: any): this {87 this.wipe(def);88 this.excludeDef.add(def);89 this.setConfigDef(def);90 return this;91 }92 // istanbul ignore next93 public async finally(callback?: (() => void) | null | undefined): Promise<IMockBuilderResult> {94 return this.then().finally(callback);95 }96 public keep(input: any, config?: IMockBuilderConfig): this {97 const { def, providers } = normaliseModule(input);98 const existing = this.keepDef.has(def) ? this.defProviders.get(def) : [];99 this.wipe(def);100 this.keepDef.add(def);101 // a magic to support modules with providers.102 if (providers) {103 this.defProviders.set(def, [...(existing || /* istanbul ignore next */ []), ...providers]);104 }105 this.setConfigDef(def, config);106 return this;107 }108 public mock(input: any, a1: any = defaultMock, a2?: any): this {109 const { def, providers } = normaliseModule(input);110 const { config, mock } = parseMockArguments(def, a1, a2, defaultMock);111 if (isNgDef(mock) && isNgDef(input) && !isNgDef(input, 't')) {112 throw new Error(113 [114 `MockBuilder.mock(${funcGetName(input)}) received a class when its shape is expected.`,115 'Please try ngMocks.defaultMock instead.',116 ].join(' '),117 );118 }119 const existing = this.mockDef.has(def) ? this.defProviders.get(def) : [];120 this.wipe(def);121 this.mockDef.add(def);122 // a magic to support modules with providers.123 if (providers) {124 this.defProviders.set(def, [...(existing || /* istanbul ignore next */ []), ...providers]);125 }126 this.setDefValue(def, mock);127 this.setConfigDef(def, config);128 return this;129 }130 public provide(def: Provider): this {131 for (const provider of flatten(def)) {132 const { provide, multi } = parseProvider(provider);133 const existing = this.providerDef.has(provide) ? this.providerDef.get(provide) : [];134 this.providerDef.set(provide, generateProviderValue(provider, existing, multi));135 }136 return this;137 }138 public replace(source: Type<any>, destination: Type<any>, config?: IMockBuilderConfig): this {139 if (!isNgDef(destination) || !isNgDef(source) || isNgDef(destination, 'i') || isNgDef(source, 'i')) {140 throw new Error(141 'Cannot replace the declaration, both have to be a Module, a Component, a Directive or a Pipe, for Providers use `.mock` or `.provide`',142 );143 }144 this.wipe(source);145 this.replaceDef.add(source);146 this.defValue.set(source, destination);147 this.setConfigDef(source, config);148 return this;149 }150 // eslint-disable-next-line unicorn/no-thenable151 public async then<TResult1 = IMockBuilderResult>(152 fulfill?: ((value: IMockBuilderResult) => PromiseLike<TResult1>) | undefined | null,153 reject?: ((reason: any) => PromiseLike<any>) | undefined | null,154 ): Promise<TResult1> {155 const promise = new Promise((resolve: (value: IMockBuilderResult) => void): void => {156 const testBed: TestBedStatic = TestBed.configureTestingModule(this.build()) as never;157 for (const callback of mapValues(this.beforeCC)) {158 callback(testBed);159 }160 const testBedPromise = testBed.compileComponents();161 testBedPromise.then(() => {162 resolve({ testBed });163 });164 });165 return promise.then(fulfill, reject);166 }167 private combineParams(): BuilderData {168 return {169 configDef: this.configDef,170 configDefault: this.configDefault,171 defProviders: this.defProviders,172 defValue: this.defValue,173 excludeDef: this.excludeDef,174 keepDef: this.keepDef,175 mockDef: this.mockDef,176 providerDef: this.providerDef,177 replaceDef: this.replaceDef,178 };179 }180 private setConfigDef(def: any, config?: any): void {181 if (config || !this.configDef.has(def)) {182 this.configDef.set(def, config ?? this.configDefault);183 }184 }185 private setDefValue(def: any, mock: any): void {186 if (mock !== defaultMock) {187 this.defValue.set(def, mock);188 } else {189 this.defValue.delete(def);190 }191 }192 private wipe(def: Type<any>): void {193 this.defProviders.delete(def);194 this.defValue.delete(def);195 this.excludeDef.delete(def);196 this.keepDef.delete(def);197 this.mockDef.delete(def);198 this.providerDef.delete(def);199 this.replaceDef.delete(def);200 }...
Using AI Code Generation
1import { ComponentFixture, TestBed } from '@angular/core/testing';2import { testBedPromise } from 'ng-mocks';3import { AppModule } from './app.module';4import { AppComponent } from './app.component';5describe('AppComponent', () => {6 let component: AppComponent;7 let fixture: ComponentFixture<AppComponent>;8 beforeEach(async () => {9 await testBedPromise({10 imports: [AppModule],11 });12 fixture = TestBed.createComponent(AppComponent);13 component = fixture.componentInstance;14 fixture.detectChanges();15 });16 it('should create', () => {17 expect(component).toBeTruthy();18 });19});20import { Component } from '@angular/core';21@Component({22})23export class AppComponent {24 title = 'my-first-angular-app';25}26import { NgModule } from '@angular/core';27import { BrowserModule } from '@angular/platform-browser';28import { AppComponent } from './app.component';29@NgModule({30 imports: [BrowserModule],31})32export class AppModule {}33import { testBedPromise } from 'ng-mocks';34import { AppModule } from './app.module';35import { AppComponent } from './app.component';36describe('AppComponent', () => {37 let component: AppComponent;38 beforeEach(async () => {39 await testBedPromise({40 imports: [AppModule],41 });42 component = TestBed.createComponent(AppComponent).componentInstance;43 });44 it('should create', () => {45 expect(component).toBeTruthy();46 });47});48import { Component } from '@angular/core';49@Component({50})51export class AppComponent {52 title = 'my-first-angular-app';53}54import { NgModule } from '@angular/core';55import { BrowserModule } from '@angular/platform-browser';56import { AppComponent } from './app.component';57@NgModule({58 imports: [BrowserModule],59})60export class AppModule {}61import { testBedPromise }
Using AI Code Generation
1import { TestBed } from '@angular/core/testing';2import { testBedPromise } from 'ng-mocks';3describe('testBedPromise', () => {4 it('should be able to use testBedPromise', async () => {5 const result = await testBedPromise();6 expect(result).toBe(true);7 });8});9import 'zone.js/dist/zone-testing';10import { getTestBed } from '@angular/core/testing';11import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';12import { testBedPromise } from 'ng-mocks';13getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());
Using AI Code Generation
1import { TestBedStatic } from '@angular/core/testing';2import { TestBed } from '@angular/core/testing';3import { AppModule } from '../src/app/app.module';4import { AppComponent } from '../src/app/app.component';5import { TestComponent } from '../src/app/test/test.component';6import { TestService } from '../src/app/test/test.service';7import { async } from 'q';8import { of } from 'rxjs';9import { By } from '@angular/platform-browser';10import { DebugElement } from '@angular/core';11describe('AppComponent', () => {12 let testBed: TestBedStatic;13 beforeEach(async(() => {14 TestBed.configureTestingModule({15 imports: [AppModule]16 }).compileComponents();17 }));18 it('should create the app', () => {19 const fixture = TestBed.createComponent(AppComponent);20 const app = fixture.debugElement.componentInstance;21 expect(app).toBeTruthy();22 });23 it(`should have as title 'test'`, () => {24 const fixture = TestBed.createComponent(AppComponent);25 const app = fixture.debugElement.componentInstance;26 expect(app.title).toEqual('test');27 });28 it('should render title in a h1 tag', () => {29 const fixture = TestBed.createComponent(AppComponent);30 fixture.detectChanges();31 const compiled = fixture.debugElement.nativeElement;32 expect(compiled.querySelector('h1').textContent).toContain('Welcome to test!');33 });34 it('should render title in a h1 tag', () => {35 const fixture = TestBed.createComponent(AppComponent);36 fixture.detectChanges();37 const compiled = fixture.debugElement.nativeElement;38 expect(compiled.querySelector('h1').textContent).toContain('Welcome to test!');39 });40 it('should render title in a h1 tag', () => {41 const fixture = TestBed.createComponent(AppComponent);42 fixture.detectChanges();43 const compiled = fixture.debugElement.nativeElement;44 expect(compiled.querySelector('h1').textContent).toContain('Welcome to test!');45 });46 it('should render title in a h1 tag', () => {47 const fixture = TestBed.createComponent(AppComponent);48 fixture.detectChanges();49 const compiled = fixture.debugElement.nativeElement;50 expect(compiled.querySelector
Using AI Code Generation
1describe('TestBedPromise', function() {2 beforeEach(function() {3 return TestBedPromise.configureTestingModule({4 });5 });6 it('should create the app', function() {7 const fixture = TestBedPromise.createComponent(TestBedPromiseComponent);8 const app = fixture.debugElement.componentInstance;9 expect(app).toBeTruthy();10 });11 it(`should have as title 'app'`, function() {12 const fixture = TestBedPromise.createComponent(TestBedPromiseComponent);13 const app = fixture.debugElement.componentInstance;14 expect(app.title).toEqual('app');15 });16});17import { Component, OnInit } from '@angular/core';18@Component({19})20export class TestBedPromiseComponent implements OnInit {21 title = 'app';22 constructor() { }23 ngOnInit() {24 }25}26import { TestBedPromise } from 'ng-mocks';27import { TestBedPromiseComponent } from './testbed-promise.component';28describe('TestBedPromiseComponent', () => {29 beforeEach(() => {30 TestBedPromise.configureTestingModule({31 });32 });33 it('should create', () => {34 const fixture = TestBedPromise.createComponent(TestBedPromiseComponent);35 const component = fixture.componentInstance;36 expect(component).toBeTruthy();37 });38});39import { TestBedPromise } from 'ng-mocks';40import { TestBedPromiseComponent } from './testbed-promise.component';41describe('TestBedPromiseComponent', () => {42 beforeEach(() => {43 TestBedPromise.configureTestingModule({44 });45 });46 it('should create', () => {47 const fixture = TestBedPromise.createComponent(TestBedPromiseComponent);48 const component = fixture.componentInstance;49 expect(component).toBeTruthy();50 });51});52import { TestBedPromise } from 'ng-mocks';53import { TestBedPromiseComponent } from './testbed-promise.component';54describe('TestBedPromiseComponent', () => {55 beforeEach(()
Using AI Code Generation
1import { TestBed } from '@angular/core/testing';2import { testBedPromise } from 'ng-mocks';3beforeEach(() => {4 return testBedPromise({5 });6});7it('should create', () => {8 const fixture = TestBed.createComponent(MyComponent);9 const component = fixture.componentInstance;10 expect(component).toBeTruthy();11});12import 'ng-mocks';13{14 "compilerOptions": {15 {16 }17 }18}19module.exports = function (config) {20 config.set({21 require('karma-jasmine'),22 require('karma-chrome-launcher'),23 require('karma-jasmine-html-reporter'),24 require('karma-coverage-istanbul-reporter'),25 require('@angular-devkit/build-angular/plugins/karma'),26 require('ng-mocks/karma'),27 });28};29{30 "compilerOptions": {31 {32 }33 }34}35{36 "projects": {37 "my-project": {38 "architect": {39 "test": {40 "options": {41 }42 }43 }44 }45 }46}47{48 "scripts": {49 },50 "devDependencies": {51 }52}
Using AI Code Generation
1import { TestBed } from 'ng-mocks';2describe('testBedPromise', () => {3 it('should work', async () => {4 const result = await TestBed.configureTestingModule({5 }).compileComponents();6 expect(result).toBeUndefined();7 });8});9import { TestBed } from 'ng-mocks';10describe('testBedPromise', () => {11 it('should work', async () => {12 const result = await TestBed.configureTestingModule({13 }).compileComponents();14 expect(result).toBeUndefined();15 });16});17import { TestBed } from 'ng-mocks';18describe('testBedPromise', () => {19 it('should work', async () => {20 const result = await TestBed.configureTestingModule({21 }).compileComponents();22 expect(result).toBeUndefined();23 });24});25{26 "compilerOptions": {27 },28}29{30 "compilerOptions": {31 "importHelpers": true,32 }33}34{35 "rules": {
Using AI Code Generation
1testBedPromise({2 imports: [MyModule],3})4.compileComponents()5.createComponent(MyComponent)6.detectChanges()7.whenStable()8.detectChanges()9.whenStable()10.detectChanges()11.whenStable()12.detectChanges()13.whenStable()14.detectChanges()15.whenStable()16.detectChanges()17.whenStable()18.detectChanges()19.whenStable()20.detectChanges()
Using AI Code Generation
1import { testBedPromise } from 'ng-mocks';2import { AppModule } from './app.module';3import { AppComponent } from './app.component';4describe('AppComponent', () => {5 it('should create the app', async () => {6 const { fixture, component } = await testBedPromise(AppModule, AppComponent, {7 });8 fixture.detectChanges();9 expect(component).toBeTruthy();10 });11});12import { testBedPromise } from 'ng-mocks';13import { AppModule } from './app.module';14import { AppComponent } from './app.component';15describe('AppComponent', () => {16 it('should create the app', async () => {17 const { fixture, component } = await testBedPromise(AppModule, AppComponent, {18 });19 fixture.detectChanges();20 expect(component).toBeTruthy();21 });22});23import { testBedPromise } from 'ng-mocks';24import { AppModule } from './app.module';25import { AppComponent } from './app.component';26describe('AppComponent', () => {27 it('should create the app', async () => {28 const { fixture, component } = await testBedPromise(AppModule, AppComponent, {29 });30 fixture.detectChanges();31 expect(component).toBeTruthy();32 });33});
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!!