How to use serviceKeep method in ng-mocks

Best JavaScript code snippet using ng-mocks

process.ts

Source:process.ts Github

copy

Full Screen

1import Bull from 'bull';2import { s3ArchiveManager } from '../../services/s3';3import { supervisorJobQueueManager } from '../supervisorJob/queue';4import { ProgressBarManager } from '../../services/jobQueue/ProgressBar';5import { JobQueueName } from '../../services/jobQueue/jobQueueName';6import {7 ScraperJobRequestData,8 ScraperMode,9 SupervisorJobRequestData,10 ScraperProgressData,11 S3JobCleanUpArgs,12 S3JobRequestData13} from '../../services/jobQueue/types';14import { Configuration } from '../../utilities/configuration';15import { getPubsubChannelName } from '../../services/jobQueue/message';16import { getMiddleReviewPageUrl } from '../../services/gd';17import { S3Organization } from '../../services/s3/types';18import { asyncSendSlackMessage } from '../../services/slack';19import { ScraperNodeScaler } from '../../services/kubernetes/kubernetesScaling';20import { KubernetesService } from '../../services/kubernetes/kubernetes';21import {22 JobQueueSharedRedisClientsSingleton,23 RedisPubSubChannelName24} from '../../services/redis';25import { SeleniumArchitectureType } from '../../services/kubernetes/types';26import { RuntimeEnvironment } from '../../utilities/runtime';27import axios from 'axios';28const asyncCleanUpS3Job = async ({29 k8sHeadServicekeepAliveScheduler30}: S3JobCleanUpArgs) => {31 console.log('s3 job enter finalizing stage');32 // stop scheduler that keeps k8s head service alive33 if (34 k8sHeadServicekeepAliveScheduler !== undefined &&35 k8sHeadServicekeepAliveScheduler !== null36 ) {37 clearInterval(k8sHeadServicekeepAliveScheduler);38 }39 // have s3 job wait till all supervisor job finished40 // as long as there is still supervisor job, we should never scale down, so keep waiting.41 // such supervisor jobs could be those dispatched by s3 job,42 // re-try from failed supervisor job from s3 job, or created manually from UI43 await new Promise((res, rej) => {44 console.log('waiting for all supervisor jobs finish');45 const scheduler = setInterval(async () => {46 try {47 const jobPresentCount = await supervisorJobQueueManager.checkConcurrency(48 1,49 undefined,50 undefined,51 undefined,52 false53 );54 process.stdout.write('.' + jobPresentCount);55 if (jobPresentCount === 0) {56 console.log('s3 job clean up supervisor job queue...');57 await supervisorJobQueueManager.asyncCleanUp();58 clearInterval(scheduler);59 return res();60 }61 } catch (error) {62 if (63 typeof error === 'string' &&64 error.includes('concurrency limit')65 ) {66 // no vacancy, which means stil some supervisor job running67 // so let's wait till them finish68 return;69 }70 // sth is wrong, don't wait just abort s3 job71 await supervisorJobQueueManager.asyncCleanUp();72 clearInterval(scheduler);73 return res();74 }75 }, 5 * 1000);76 try {77 JobQueueSharedRedisClientsSingleton.singleton.onTerminate(78 async () => {79 console.log(80 's3 job receives terminate signal while finalizing, will now force proceeding clean up'81 );82 clearInterval(scheduler);83 await supervisorJobQueueManager.asyncCleanUp();84 return res(`maunallyTerminated`);85 }86 );87 } catch (error) {88 rej(error);89 }90 });91 // cool down92 try {93 const res = await asyncSendSlackMessage(94 `S3 work done, best effort scaled down selenium microservice`95 );96 } catch (error) {97 console.log(98 error instanceof Error ? error.message : error,99 'slack request failed'100 );101 }102 console.log('about to scale down selenium, cool down for 10 seconds');103 await new Promise(res => setTimeout(res, 10 * 1000));104 // best effort scale down selenium resources and nodes105 await ScraperNodeScaler.singleton.scaleDown().then(async () => {106 try {107 await asyncSendSlackMessage(108 `=== S3 job scaled down node pools, finalize stage complete ===`109 );110 } catch (error) {}111 });112};113const getSplittedJobRequestData = (114 org: S3Organization,115 pageNumberPointer: number,116 incrementalPageAmount: number,117 shardIndex: number,118 jobSplitedSize: number119) => {120 return {121 // job splitting params122 nextReviewPageUrl: getMiddleReviewPageUrl(123 org.reviewPageUrl,124 pageNumberPointer + 1125 ),126 stopPage: pageNumberPointer + incrementalPageAmount,127 // other essential params128 pubsubChannelName: getPubsubChannelName({129 orgName: org.orgName,130 page: pageNumberPointer + 1131 }),132 orgId: org.orgId,133 orgName: org.orgName,134 scrapeMode: ScraperMode.RENEWAL,135 // for log and monitor136 shardIndex,137 lastProgress: {138 processed: 0,139 wentThrough: 0,140 total: jobSplitedSize,141 durationInMilli: '1',142 page: pageNumberPointer,143 processedSession: 0144 }145 };146};147module.exports = function (s3OrgsJob: Bull.Job<S3JobRequestData>) {148 console.log(`s3OrgsJob ${s3OrgsJob.id} started`, s3OrgsJob);149 supervisorJobQueueManager.initialize(`s3Org sandbox`, false);150 const progressBarManager = ProgressBarManager.newProgressBarManager(151 JobQueueName.GD_ORG_REVIEW_S3_ORGS_JOB,152 s3OrgsJob153 );154 // register pubsub for job termination155 JobQueueSharedRedisClientsSingleton.singleton.intialize('s3Org');156 JobQueueSharedRedisClientsSingleton.singleton.subscriberClient157 ?.subscribe(RedisPubSubChannelName.ADMIN)158 .then(count => {159 console.log(160 's3 subscribed to admin channel successfully; count',161 count162 );163 });164 // first check if there's any node pool created165 return KubernetesService.singleton166 .getReadyNodePool('scraperWorker')167 .then(async readyNodePool => {168 // make sure node pool is created169 if (!readyNodePool) {170 const res = await KubernetesService.singleton._createScraperWorkerNodePool(171 Configuration.singleton.autoDigitaloceanDropletSize172 );173 console.log(res.size, 'node pool created');174 }175 // polling till all nodes in pool ready176 return await new Promise(177 (resolvePollingPromise, rejectPollingPromise) => {178 console.log('polling node and selenium stack readiness');179 const scheduler = setInterval(async () => {180 try {181 const readyNodePool = await KubernetesService.singleton.getReadyNodePool(182 'scraperWorker',183 true184 );185 try {186 if (!readyNodePool) {187 await asyncSendSlackMessage(188 `Polling node pool status: \`(No ready node pool yet)\`.`189 );190 } else {191 await asyncSendSlackMessage(192 'Polling node pool status:\n' +193 `\`\`\`\n${JSON.stringify(194 readyNodePool195 )}\n\`\`\`\n`196 );197 }198 } catch (error) {}199 if (readyNodePool) {200 clearInterval(scheduler);201 console.log(202 'nodes are ready, next is to create selenium base...'203 );204 // create selenium base205 await ScraperNodeScaler.singleton.orderSeleniumBaseProvisioning();206 // if pod-standalone architecuture, then no need to wait for additional resources207 if (208 Configuration.singleton209 .seleniumArchitectureType ===210 SeleniumArchitectureType['pod-standalone']211 ) {212 // wait for 10 seconds to cool down213 console.log(214 'selenium base created, cooling down before starting s3...'215 );216 await new Promise(res =>217 setTimeout(res, 10 * 1000)218 );219 } else if (220 Configuration.singleton221 .seleniumArchitectureType ===222 SeleniumArchitectureType['hub-node']223 ) {224 // TODO:225 // if node-chrome architecture, need to further deploy chrome nodes and226 // wait for 1) hub deployment 2) all chrome nodes deployment status227 // to be 'has minimum availability'228 await ScraperNodeScaler.singleton.orderSeleniumChromeNodeProvisioning();229 // here we just blindly wait for 5 minutes, but ideally we want to230 // do polling and see deployments are ready231 console.log(232 'nodes are ready, selenium base and chrome node deployment created. Wait 5 minutes before starting s3 job'233 );234 await new Promise(res =>235 setTimeout(res, 5 * 60 * 1000)236 );237 } else {238 // unknown selenium archi type, move forward anyway239 console.log(240 'unknown selenium archi type, s3 job move forward anyway'241 );242 }243 return resolvePollingPromise();244 }245 process.stdout.write('.');246 } catch (error) {247 clearInterval(scheduler);248 throw error;249 }250 }, 10 * 1000);251 try {252 JobQueueSharedRedisClientsSingleton.singleton.onTerminate(253 () => {254 clearInterval(scheduler);255 return resolvePollingPromise(256 `manuallyTerminated`257 );258 }259 );260 } catch (error) {261 clearInterval(scheduler);262 return rejectPollingPromise(263 `failed to register redis termination signal while polling node pool in s3 job`264 );265 }266 }267 );268 })269 .then(async () => {270 try {271 return await asyncSendSlackMessage(272 `Now proceed s3 job dispatching, s3 job data:\n\`\`\`${JSON.stringify(273 s3OrgsJob.data || 'Null'274 )}\`\`\` `275 );276 } catch {}277 })278 .then(() => {279 // keep alive for k8s head service hosted on Heroku280 // we're polling per 60 seconds, but should be just fine at least polling once for an hour281 const k8sHeadServicekeepAliveScheduler = s3OrgsJob.data282 ?.keepAliveK8sHeadService283 ? setInterval(async () => {284 try {285 await axios.get(286 process.env.NODE_ENV ===287 RuntimeEnvironment.DEVELOPMENT288 ? `http://host.docker.internal:3010/`289 : `https://k8s-cluster-head-service.herokuapp.com/`290 );291 } catch (error) {}292 }, 60 * 1000)293 : undefined;294 return (295 s3ArchiveManager296 .asyncGetAllOrgsForS3Job()297 // increment progress after s3 org list fetched298 .then(orgList =>299 progressBarManager300 .increment()301 .then(async () => {302 const supervisorJobRequests: SupervisorJobRequestData[] = [];303 for (const org of orgList) {304 // dispatch for large org (splitted job)305 if (306 org.reviewPageUrl &&307 org.localReviewCount &&308 org.localReviewCount >309 Configuration.singleton310 .scraperJobSplittingSize311 ) {312 const incrementalPageAmount = Math.ceil(313 Configuration.singleton314 .scraperJobSplittingSize /315 Configuration.singleton316 .gdReviewCountPerPage317 );318 const jobSplitedSize =319 incrementalPageAmount *320 Configuration.singleton321 .gdReviewCountPerPage;322 let pageNumberPointer = 0;323 let shardIndex = 0;324 // dispatch 1st job325 supervisorJobRequests.push({326 splittedScraperJobRequestData: getSplittedJobRequestData(327 org,328 pageNumberPointer,329 incrementalPageAmount,330 shardIndex,331 jobSplitedSize332 )333 });334 pageNumberPointer += incrementalPageAmount;335 shardIndex += 1;336 // dispatch rest of the parts337 const estimatedPageCountTotal = Math.ceil(338 org.localReviewCount /339 Configuration.singleton340 .gdReviewCountPerPage341 );342 while (343 pageNumberPointer <344 estimatedPageCountTotal345 ) {346 supervisorJobRequests.push({347 splittedScraperJobRequestData: getSplittedJobRequestData(348 org,349 pageNumberPointer,350 incrementalPageAmount,351 shardIndex,352 jobSplitedSize353 )354 });355 pageNumberPointer += incrementalPageAmount;356 shardIndex += 1;357 }358 // last splitted job does not need stop page, just scrape till the end359 delete (supervisorJobRequests[360 supervisorJobRequests.length - 1361 ]362 .splittedScraperJobRequestData as ScraperJobRequestData)363 .stopPage;364 // correct last splitted job to use the remained value365 ((supervisorJobRequests[366 supervisorJobRequests.length - 1367 ]368 .splittedScraperJobRequestData as ScraperJobRequestData)369 .lastProgress as ScraperProgressData).total =370 org.localReviewCount %371 jobSplitedSize;372 continue;373 }374 // dispatch for small org that does not need splitting375 supervisorJobRequests.push({376 scraperJobRequestData: {377 pubsubChannelName: getPubsubChannelName(378 {379 orgName: org.orgName380 }381 ),382 orgInfo: org.companyOverviewPageUrl383 }384 });385 }386 // report progress after job planning complete387 try {388 if (!supervisorJobRequests.length) {389 await progressBarManager.syncSetAbsolutePercentage(390 100391 );392 } else {393 await progressBarManager.syncSetRelativePercentage(394 0,395 supervisorJobRequests.length396 );397 }398 } catch (error) {}399 return supervisorJobRequests;400 })401 .then(scraperJobRequests => {402 // dispatch job and wait for job complete403 return Promise.all(404 scraperJobRequests.map(405 (scraperJobRequest, index) => {406 return new Promise<string>(407 (res, rej) => {408 const scheduler = setTimeout(409 async () => {410 try {411 const job = await supervisorJobQueueManager.asyncAdd(412 scraperJobRequest413 );414 const result: string = await job.finished();415 await progressBarManager.increment();416 return res(417 result418 );419 } catch (error) {420 let errorMessage: string;421 if (422 error instanceof423 Error424 ) {425 errorMessage =426 error.message;427 } else if (428 typeof error ===429 'string'430 ) {431 errorMessage = error;432 } else {433 errorMessage = JSON.stringify(434 error || {435 message:436 'empty error'437 }438 );439 }440 // if it's a manual termination request, withdraw this s3 job441 // otherwise let us keep waiting other remaining job's .finished() to resolve442 const normalizedText = errorMessage.toLowerCase();443 if (444 normalizedText.includes(445 'manual'446 ) &&447 normalizedText.includes(448 'terminate'449 )450 ) {451 return rej(452 new Error(453 errorMessage454 )455 );456 }457 // s3 job move on anyway458 await progressBarManager.increment();459 return res(460 errorMessage461 );462 }463 },464 index *465 Configuration466 .singleton467 .s3DispatchJobIntervalMs468 );469 // terminate all jobs when signaled from pubsub470 JobQueueSharedRedisClientsSingleton.singleton.onTerminate(471 () => {472 clearTimeout(473 scheduler474 );475 return res(476 `maunallyTerminated`477 );478 }479 );480 }481 );482 }483 )484 );485 })486 )487 .then(async (resultList: string[]) => {488 await asyncCleanUpS3Job({489 k8sHeadServicekeepAliveScheduler490 });491 return resultList;492 })493 .catch(async (error: Error) => {494 await asyncCleanUpS3Job({495 k8sHeadServicekeepAliveScheduler496 });497 throw error;498 })499 );500 })501 .catch(error => {502 // s3 job failed to initialize503 throw error;504 });...

Full Screen

Full Screen

test.ng-mocks.spec.ts

Source:test.ng-mocks.spec.ts Github

copy

Full Screen

1import { HttpClientModule } from '@angular/common/http';2import { HttpClientTestingModule } from '@angular/common/http/testing';3import { inject, TestBed } from '@angular/core/testing';4import { isMockedNgDefOf, MockBuilder, NG_MOCKS } from 'ng-mocks';5import {6 KeepComponent,7 MockComponent,8 My1Component,9 My2Component,10 My3Component,11 MyComponent,12} from './spec.components.fixtures';13import {14 KeepDirective,15 MockDirective,16} from './spec.directives.fixtures';17import {18 ModuleKeep,19 ModuleMock,20 MyModule,21} from './spec.modules.fixtures';22import {23 KeepPipe,24 MockPipe,25 RestorePipe,26} from './spec.pipes.fixtures';27import {28 ServiceCustomize,29 ServiceKeep,30 ServiceMock,31} from './spec.services.fixtures';32import {33 TOKEN_CUSTOMIZE,34 TOKEN_KEEP,35 TOKEN_MOCK,36} from './spec.tokens.fixtures';37describe('MockBuilder:ngMocks', () => {38 beforeEach(async () => {39 const ngModule = MockBuilder(MyComponent, MyModule)40 .keep(ModuleKeep)41 .keep(KeepComponent)42 .keep(KeepDirective)43 .keep(KeepPipe)44 .keep(ServiceKeep)45 .keep(TOKEN_KEEP)46 .replace(HttpClientModule, HttpClientTestingModule)47 .mock(ModuleMock)48 .mock(MockComponent)49 .mock(MockDirective)50 .mock(MockPipe)51 .mock(ServiceMock) // makes all methods an empty function52 .mock(TOKEN_MOCK) // makes its value undefined53 .mock(ServiceCustomize, {54 getName: () => 'My Customized String',55 })56 .mock(TOKEN_CUSTOMIZE, 'My_Token')57 // Now the pipe will not be replaced with its mock copy.58 .keep(RestorePipe)59 // Even it belongs to the module we want to keep,60 // it will be still replaced with a mock copy.61 .mock(My3Component)62 // and now we want to build our NgModule.63 .build();64 TestBed.configureTestingModule(ngModule);65 // Extra configuration66 TestBed.overrideTemplate(67 My1Component,68 'If we need to tune testBed',69 );70 TestBed.overrideTemplate(My2Component, 'More callbacks');71 return TestBed.compileComponents();72 });73 it('should contain mocks', inject(74 [NG_MOCKS],75 (mocks: Map<any, any>) => {76 // main part77 const myComponent = mocks.get(MyComponent);78 expect(myComponent).toBe(MyComponent);79 const myModule = mocks.get(MyModule);80 expect(isMockedNgDefOf(myModule, MyModule, 'm')).toBeTruthy();81 // keep82 const keepComponent = mocks.get(KeepComponent);83 expect(keepComponent).toBe(keepComponent);84 const keepDirective = mocks.get(KeepDirective);85 expect(keepDirective).toBe(keepDirective);86 const keepPipe = mocks.get(KeepPipe);87 expect(keepPipe).toBe(keepPipe);88 const serviceKeep = mocks.get(ServiceKeep);89 expect(serviceKeep).toBe(ServiceKeep);90 const tokenKeep = mocks.get(TOKEN_KEEP);91 expect(tokenKeep).toBe(TOKEN_KEEP);92 // replace93 const httpClientModule = mocks.get(HttpClientModule);94 expect(httpClientModule).toBe(HttpClientTestingModule);95 // mimic96 const moduleMock = mocks.get(ModuleMock);97 expect(98 isMockedNgDefOf(moduleMock, ModuleMock, 'm'),99 ).toBeTruthy();100 const mockComponent = mocks.get(MockComponent);101 expect(102 isMockedNgDefOf(mockComponent, MockComponent, 'c'),103 ).toBeTruthy();104 const mockDirective = mocks.get(MockDirective);105 expect(106 isMockedNgDefOf(mockDirective, MockDirective, 'd'),107 ).toBeTruthy();108 const mockPipe = mocks.get(MockPipe);109 expect(isMockedNgDefOf(mockPipe, MockPipe, 'p')).toBeTruthy();110 const serviceMock = mocks.get(ServiceMock);111 expect(serviceMock).toBeDefined();112 expect(serviceMock.useFactory).toBeDefined();113 const serviceMockInstance = serviceMock.useFactory();114 expect(serviceMockInstance.getName).toBeDefined();115 expect(serviceMockInstance.getName()).toBeUndefined();116 expect(mocks.has(TOKEN_MOCK)).toBeDefined();117 expect(mocks.get(TOKEN_MOCK)).toBeDefined();118 // customize119 const serviceCustomize = mocks.get(ServiceCustomize);120 expect(serviceCustomize).toBeDefined();121 expect(serviceCustomize.useFactory).toBeDefined();122 const serviceCustomizeInstance = serviceCustomize.useFactory();123 expect(serviceCustomizeInstance.getName).toBeDefined();124 expect(serviceCustomizeInstance.getName()).toEqual(125 'My Customized String',126 );127 const tokenCustomize = mocks.get(TOKEN_CUSTOMIZE);128 expect(tokenCustomize).toBeDefined();129 expect(tokenCustomize.useFactory).toBeDefined();130 const tokenCustomizeValue = tokenCustomize.useFactory();131 expect(tokenCustomizeValue).toEqual('My_Token');132 // restore133 const restorePipe = mocks.get(RestorePipe);134 expect(restorePipe).toBe(restorePipe);135 // mock nested136 const myComponent3 = mocks.get(My3Component);137 expect(138 isMockedNgDefOf(myComponent3, My3Component, 'c'),139 ).toBeTruthy();140 },141 ));...

Full Screen

Full Screen

spec.components.fixtures.ts

Source:spec.components.fixtures.ts Github

copy

Full Screen

1import { Component, ContentChild, Inject, Input, Optional, TemplateRef } from '@angular/core';2import {3 AnythingKeep1,4 AnythingKeep2,5 MyCustomProvider1,6 MyCustomProvider2,7 MyCustomProvider3,8 MyService1,9 MyService2,10 ServiceCustomize,11 ServiceKeep,12 ServiceMock,13} from './spec.services.fixtures';14import { TOKEN_CUSTOMIZE, TOKEN_KEEP, TOKEN_MOCK } from './spec.tokens.fixtures';15@Component({16 selector: 'c-structural',17 template: `18 <div *ngIf="items && items.length">19 <ng-template ngFor [ngForOf]="items" [ngForTemplate]="injectedBlock"></ng-template>20 </div>21 `,22})23export class ContentChildComponent<T> {24 @ContentChild('block', {} as any) public readonly injectedBlock: TemplateRef<any> | undefined;25 @Input() public items: T[] | undefined;26}27@Component({28 selector: 'c-my',29 template: `30 <div>My Content</div>31 <div>MyComponent1: <c-1></c-1></div>32 <div>MyComponent2: <c-2></c-2></div>33 <div>MyComponent3: <c-3></c-3></div>34 <div>KeepComponent: <c-keep></c-keep></div>35 <div>MockComponent: <c-mock></c-mock></div>36 <div>MyDirective: <d-my></d-my></div>37 <div>KeepDirective: <d-keep></d-keep></div>38 <div>39 MockDirective 1: <span *d-mock="let z = a">render {{ z.b }}</span>40 </div>41 <div>42 MockDirective 2: <ng-template d-mock let-z>render {{ z.a }}</ng-template>43 </div>44 <div>MyPipe: {{ 'text' | my }}</div>45 <div>KeepPipe: {{ 'text' | keep }}</div>46 <div>MockPipe: {{ 'text' | mock }}</div>47 <div>CustomizePipe: {{ 'text' | customize }}</div>48 <div>RestorePipe: {{ 'text' | restore }}</div>49 <div>TOKEN_KEEP: {{ t1 }}</div>50 <div>TOKEN_MOCK: {{ t2 }}</div>51 <div>TOKEN_CUSTOMIZE: {{ t3 }}</div>52 <div>AnythingKeep1: {{ anythingKeep1?.getName() }}</div>53 <div>AnythingKeep2: {{ anythingKeep2?.getName() }}</div>54 <div>myCustomProvider1: {{ myCustomProvider1?.getName() }}</div>55 <div>myCustomProvider2: {{ myCustomProvider2?.getName() }}</div>56 <div>myCustomProvider3: {{ myCustomProvider3?.getName() }}</div>57 <div>myService1: {{ myService1?.getName() }}</div>58 <div>myService2: {{ myService2?.getName() }}</div>59 <div>serviceKeep: {{ serviceKeep?.getName() }}</div>60 <div>serviceCustomize: {{ serviceCustomize?.getName() }}</div>61 <div>serviceMock: {{ serviceMock?.getName() }}</div>62 <c-structural>63 <ng-template let-value let-b="a" #block>64 <div>ComponentStructural: {{ value }} {{ b.z }}</div>65 </ng-template>66 </c-structural>67 `,68})69export class MyComponent {70 public constructor(71 @Optional() @Inject(TOKEN_KEEP) public readonly t1: string,72 @Optional() @Inject(TOKEN_MOCK) public readonly t2: string,73 @Optional() @Inject(TOKEN_CUSTOMIZE) public readonly t3: string,74 @Optional() public readonly anythingKeep1: AnythingKeep1,75 @Optional() public readonly anythingKeep2: AnythingKeep2,76 @Optional() public readonly myCustomProvider1: MyCustomProvider1,77 @Optional() public readonly myCustomProvider2: MyCustomProvider2,78 @Optional() public readonly myCustomProvider3: MyCustomProvider3,79 @Optional() public readonly myService1: MyService1,80 @Optional() public readonly myService2: MyService2,81 @Optional() public readonly serviceKeep: ServiceKeep,82 @Optional() public readonly serviceMock: ServiceMock,83 @Optional() public readonly serviceCustomize: ServiceCustomize,84 ) {}85}86@Component({87 selector: 'c-1',88 template: 'MyComponent1',89})90export class My1Component {}91@Component({92 selector: 'c-2',93 template: 'MyComponent2',94})95export class My2Component {}96@Component({97 selector: 'c-3',98 template: 'MyComponent3',99})100export class My3Component {}101@Component({102 selector: 'c-keep',103 template: 'KeepComponent',104})105export class KeepComponent {}106@Component({107 selector: 'c-mock',108 template: 'MockComponent',109})...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('test', function() {2 beforeEach(module('test'));3 var $serviceKeep;4 beforeEach(inject(function(_$serviceKeep_) {5 $serviceKeep = _$serviceKeep_;6 }));7 it('should keep service', function() {8 $serviceKeep('service');9 });10});11describe('test', function() {12 beforeEach(module('test'));13 var $serviceKeep;14 beforeEach(inject(function(_$serviceKeep_) {15 $serviceKeep = _$serviceKeep_;16 }));17 it('should keep service', function() {18 $serviceKeep('service');19 });20});21describe('test', function() {22 beforeEach(module('test'));23 var $serviceKeep;24 beforeEach(inject(function(_$serviceKeep_) {25 $serviceKeep = _$serviceKeep_;26 }));27 it('should keep service', function() {28 $serviceKeep('service');29 });30});31describe('test', function() {32 beforeEach(module('test'));33 var $serviceKeep;34 beforeEach(inject(function(_$serviceKeep_) {35 $serviceKeep = _$serviceKeep_;36 }));37 it('should keep service', function() {38 $serviceKeep('service');39 });40});41describe('test', function() {42 beforeEach(module('test'));43 var $serviceKeep;44 beforeEach(inject(function(_$serviceKeep_) {45 $serviceKeep = _$serviceKeep_;46 }));47 it('should keep service', function() {48 $serviceKeep('service');49 });50});51describe('test', function() {52 beforeEach(module('test'));53 var $serviceKeep;54 beforeEach(inject(function(_$serviceKeep_) {55 $serviceKeep = _$serviceKeep_;56 }));57 it('should keep service', function() {58 $serviceKeep('service');59 });60});61describe('test', function() {62 beforeEach(module('test'));

Full Screen

Using AI Code Generation

copy

Full Screen

1var serviceKeep = ngMocks.serviceKeep('service');2ngMocks.serviceReset('service');3ngMocks.serviceReplace('service', service);4var serviceKeep = ngMocks.serviceKeep('service');5ngMocks.serviceReset();6ngMocks.serviceReplace('service', service);7var serviceKeep = ngMocks.serviceKeep('service');8ngMocks.serviceReset('service');9ngMocks.serviceReplace('service', service);10var serviceKeep = ngMocks.serviceKeep('service');11ngMocks.serviceReset();12ngMocks.serviceReplace('service', service);13var serviceKeep = ngMocks.serviceKeep('service');14ngMocks.serviceReset('service');15ngMocks.serviceReplace('service', service);16var serviceKeep = ngMocks.serviceKeep('service');17ngMocks.serviceReset();18ngMocks.serviceReplace('service', service);19var serviceKeep = ngMocks.serviceKeep('service');20ngMocks.serviceReset('service');21ngMocks.serviceReplace('service', service);22var serviceKeep = ngMocks.serviceKeep('service');23ngMocks.serviceReset();

Full Screen

Using AI Code Generation

copy

Full Screen

1angular.module('test', [])2 .service('testService', function() {3 this.test = function() {4 return 'test';5 }6 })7 .controller('testCtrl', function($scope, testService) {8 $scope.test = testService.test();9 });10describe('testCtrl', function() {11 var $scope, $controller, testService;12 beforeEach(function() {13 module('test');14 module('ngMock');15 inject(function($rootScope, _$controller_, _testService_) {16 $scope = $rootScope.$new();17 $controller = _$controller_;18 testService = _testService_;19 });20 testService.test = function() {21 return 'mockTest';22 };23 });24 it('should be able to mock service', function() {25 $controller('testCtrl', {26 });27 expect($scope.test).toEqual('mockTest');28 });29});

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test', () => {2 beforeEach(() => {3 });4 it('should be defined', () => {5 expect(HomeModule).toBeDefined();6 });7});8@NgModule({9 imports: [CommonModule, HomeRoutingModule],10})11export class HomeModule {}12@Injectable()13export class HomeService {}14@Component({15})16export class HomeComponent implements OnInit {17 constructor(private homeService: HomeService) {}18 ngOnInit(): void {}19}20 {21 }22];23@NgModule({24 imports: [RouterModule.forChild(routes)],25})26export class HomeRoutingModule {}27h1 {28 color: red;29}30import { async, ComponentFixture, TestBed } from '@angular/core/testing';31import { HomeComponent } from './home.component';32describe('HomeComponent', () => {33 let component: HomeComponent;34 let fixture: ComponentFixture<HomeComponent>;35 beforeEach(async(() => {36 TestBed.configureTestingModule({37 }).compileComponents();38 }));39 beforeEach(() => {40 fixture = TestBed.createComponent(HomeComponent);41 component = fixture.componentInstance;42 fixture.detectChanges();43 });44 it('should create', () => {45 expect(component).toBeTruthy();46 });47});48@NgModule({49 imports: [BrowserModule, AppRoutingModule, HomeModule],50})51export class AppModule {}

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('ServiceKeep', function () {2 beforeEach(function () {3 serviceKeep('ServiceName');4 });5 it('should not be undefined', function () {6 expect(ServiceName).not.toBe(undefined);7 });8});9describe('ServiceKeep', function () {10 beforeEach(function () {11 serviceKeep('ServiceName');12 });13 it('should not be undefined', function () {14 expect(ServiceName).not.toBe(undefined);15 });16});17describe('ServiceKeep', function () {18 beforeEach(function () {19 serviceKeep('ServiceName');20 });21 it('should not be undefined', function () {22 expect(ServiceName).not.toBe(undefined);23 });24});25describe('ServiceKeep', function () {26 beforeEach(function () {27 serviceKeep('ServiceName');28 });29 it('should not be undefined', function () {30 expect(ServiceName).not.toBe(undefined);31 });32});

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run ng-mocks automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful