How to use MockService method in ng-mocks

Best JavaScript code snippet using ng-mocks

test_bookmark_repair_requestor.js

Source:test_bookmark_repair_requestor.js Github

copy

Full Screen

...67 req._now = () => Date.now() / 1000; // _now() is seconds.68 return req;69}70add_task(async function test_requestor_no_clients() {71 let mockService = new MockService({ });72 let requestor = NewBookmarkRepairRequestor(mockService);73 let validationInfo = {74 problems: {75 missingChildren: [76 {parent: "x", child: "a"},77 {parent: "x", child: "b"},78 {parent: "x", child: "c"},79 ],80 orphans: [],81 },82 };83 let flowID = Utils.makeGUID();84 await requestor.startRepairs(validationInfo, flowID);85 // there are no clients, so we should end up in "finished" (which we need to86 // check via telemetry)87 deepEqual(mockService._recordedEvents, [88 { object: "repair",89 method: "started",90 value: undefined,91 extra: { flowID, numIDs: 4 },92 },93 { object: "repair",94 method: "finished",95 value: undefined,96 extra: { flowID, numIDs: 4 },97 },98 ]);99});100add_task(async function test_requestor_one_client_no_response() {101 let mockService = new MockService({ "client-a": makeClientRecord("client-a") });102 let requestor = NewBookmarkRepairRequestor(mockService);103 let validationInfo = {104 problems: {105 missingChildren: [106 {parent: "x", child: "a"},107 {parent: "x", child: "b"},108 {parent: "x", child: "c"},109 ],110 orphans: [],111 },112 };113 let flowID = Utils.makeGUID();114 await requestor.startRepairs(validationInfo, flowID);115 // the command should now be outgoing.116 checkOutgoingCommand(mockService, "client-a");117 checkState(BookmarkRepairRequestor.STATE.SENT_REQUEST);118 // asking it to continue stays in that state until we timeout or the command119 // is removed.120 await requestor.continueRepairs();121 checkState(BookmarkRepairRequestor.STATE.SENT_REQUEST);122 // now pretend that client synced.123 mockService.clientsEngine._sentCommands = {};124 await requestor.continueRepairs();125 checkState(BookmarkRepairRequestor.STATE.SENT_SECOND_REQUEST);126 // the command should be outgoing again.127 checkOutgoingCommand(mockService, "client-a");128 // pretend that client synced again without writing a command.129 mockService.clientsEngine._sentCommands = {};130 await requestor.continueRepairs();131 // There are no more clients, so we've given up.132 checkRepairFinished();133 deepEqual(mockService._recordedEvents, [134 { object: "repair",135 method: "started",136 value: undefined,137 extra: { flowID, numIDs: 4 },138 },139 { object: "repair",140 method: "request",141 value: "upload",142 extra: { flowID, numIDs: 4, deviceID: "client-a" },143 },144 { object: "repair",145 method: "request",146 value: "upload",147 extra: { flowID, numIDs: 4, deviceID: "client-a" },148 },149 { object: "repair",150 method: "finished",151 value: undefined,152 extra: { flowID, numIDs: 4 },153 },154 ]);155});156add_task(async function test_requestor_one_client_no_sync() {157 let mockService = new MockService({ "client-a": makeClientRecord("client-a") });158 let requestor = NewBookmarkRepairRequestor(mockService);159 let validationInfo = {160 problems: {161 missingChildren: [162 {parent: "x", child: "a"},163 {parent: "x", child: "b"},164 {parent: "x", child: "c"},165 ],166 orphans: [],167 },168 };169 let flowID = Utils.makeGUID();170 await requestor.startRepairs(validationInfo, flowID);171 // the command should now be outgoing.172 checkOutgoingCommand(mockService, "client-a");173 checkState(BookmarkRepairRequestor.STATE.SENT_REQUEST);174 // pretend we are now in the future.175 let theFuture = Date.now() + 300000000;176 requestor._now = () => theFuture;177 await requestor.continueRepairs();178 // We should be finished as we gave up in disgust.179 checkRepairFinished();180 deepEqual(mockService._recordedEvents, [181 { object: "repair",182 method: "started",183 value: undefined,184 extra: { flowID, numIDs: 4 },185 },186 { object: "repair",187 method: "request",188 value: "upload",189 extra: { flowID, numIDs: 4, deviceID: "client-a" },190 },191 { object: "repair",192 method: "abandon",193 value: "silent",194 extra: { flowID, deviceID: "client-a" },195 },196 { object: "repair",197 method: "finished",198 value: undefined,199 extra: { flowID, numIDs: 4 },200 },201 ]);202});203add_task(async function test_requestor_latest_client_used() {204 let mockService = new MockService({205 "client-early": makeClientRecord("client-early", { serverLastModified: Date.now() - 10 }),206 "client-late": makeClientRecord("client-late", { serverLastModified: Date.now() }),207 });208 let requestor = NewBookmarkRepairRequestor(mockService);209 let validationInfo = {210 problems: {211 missingChildren: [212 { parent: "x", child: "a" },213 ],214 orphans: [],215 },216 };217 await requestor.startRepairs(validationInfo, Utils.makeGUID());218 // the repair command should be outgoing to the most-recent client.219 checkOutgoingCommand(mockService, "client-late");220 checkState(BookmarkRepairRequestor.STATE.SENT_REQUEST);221 // and this test is done - reset the repair.222 requestor.prefs.resetBranch();223});224add_task(async function test_requestor_client_vanishes() {225 let mockService = new MockService({226 "client-a": makeClientRecord("client-a"),227 "client-b": makeClientRecord("client-b"),228 });229 let requestor = NewBookmarkRepairRequestor(mockService);230 let validationInfo = {231 problems: {232 missingChildren: [233 {parent: "x", child: "a"},234 {parent: "x", child: "b"},235 {parent: "x", child: "c"},236 ],237 orphans: [],238 },239 };240 let flowID = Utils.makeGUID();241 await requestor.startRepairs(validationInfo, flowID);242 // the command should now be outgoing.243 checkOutgoingCommand(mockService, "client-a");244 checkState(BookmarkRepairRequestor.STATE.SENT_REQUEST);245 mockService.clientsEngine._sentCommands = {};246 // Now let's pretend the client vanished.247 delete mockService.clientsEngine._clientList["client-a"];248 await requestor.continueRepairs();249 // We should have moved on to client-b.250 checkState(BookmarkRepairRequestor.STATE.SENT_REQUEST);251 checkOutgoingCommand(mockService, "client-b");252 // Now let's pretend client B wrote all missing IDs.253 let response = {254 collection: "bookmarks",255 request: "upload",256 flowID: requestor._flowID,257 clientID: "client-b",258 ids: ["a", "b", "c", "x"],259 };260 await requestor.continueRepairs(response);261 // We should be finished as we got all our IDs.262 checkRepairFinished();263 deepEqual(mockService._recordedEvents, [264 { object: "repair",265 method: "started",266 value: undefined,267 extra: { flowID, numIDs: 4 },268 },269 { object: "repair",270 method: "request",271 value: "upload",272 extra: { flowID, numIDs: 4, deviceID: "client-a" },273 },274 { object: "repair",275 method: "abandon",276 value: "missing",277 extra: { flowID, deviceID: "client-a" },278 },279 { object: "repair",280 method: "request",281 value: "upload",282 extra: { flowID, numIDs: 4, deviceID: "client-b" },283 },284 { object: "repair",285 method: "response",286 value: "upload",287 extra: { flowID, deviceID: "client-b", numIDs: 4 },288 },289 { object: "repair",290 method: "finished",291 value: undefined,292 extra: { flowID, numIDs: 0 },293 },294 ]);295});296add_task(async function test_requestor_success_responses() {297 let mockService = new MockService({298 "client-a": makeClientRecord("client-a"),299 "client-b": makeClientRecord("client-b"),300 });301 let requestor = NewBookmarkRepairRequestor(mockService);302 let validationInfo = {303 problems: {304 missingChildren: [305 {parent: "x", child: "a"},306 {parent: "x", child: "b"},307 {parent: "x", child: "c"},308 ],309 orphans: [],310 },311 };312 let flowID = Utils.makeGUID();313 await requestor.startRepairs(validationInfo, flowID);314 // the command should now be outgoing.315 checkOutgoingCommand(mockService, "client-a");316 checkState(BookmarkRepairRequestor.STATE.SENT_REQUEST);317 mockService.clientsEngine._sentCommands = {};318 // Now let's pretend the client wrote a response.319 let response = {320 collection: "bookmarks",321 request: "upload",322 clientID: "client-a",323 flowID: requestor._flowID,324 ids: ["a", "b"],325 };326 await requestor.continueRepairs(response);327 // We should have moved on to client 2.328 checkState(BookmarkRepairRequestor.STATE.SENT_REQUEST);329 checkOutgoingCommand(mockService, "client-b");330 // Now let's pretend client B write the missing ID.331 response = {332 collection: "bookmarks",333 request: "upload",334 clientID: "client-b",335 flowID: requestor._flowID,336 ids: ["c", "x"],337 };338 await requestor.continueRepairs(response);339 // We should be finished as we got all our IDs.340 checkRepairFinished();341 deepEqual(mockService._recordedEvents, [342 { object: "repair",343 method: "started",344 value: undefined,345 extra: { flowID, numIDs: 4 },346 },347 { object: "repair",348 method: "request",349 value: "upload",350 extra: { flowID, numIDs: 4, deviceID: "client-a" },351 },352 { object: "repair",353 method: "response",354 value: "upload",355 extra: { flowID, deviceID: "client-a", numIDs: 2 },356 },357 { object: "repair",358 method: "request",359 value: "upload",360 extra: { flowID, numIDs: 2, deviceID: "client-b" },361 },362 { object: "repair",363 method: "response",364 value: "upload",365 extra: { flowID, deviceID: "client-b", numIDs: 2 },366 },367 { object: "repair",368 method: "finished",369 value: undefined,370 extra: { flowID, numIDs: 0 },371 },372 ]);373});374add_task(async function test_client_suitability() {375 let mockService = new MockService({376 "client-a": makeClientRecord("client-a"),377 "client-b": makeClientRecord("client-b", { type: "mobile" }),378 "client-c": makeClientRecord("client-c", { version: "52.0a1" }),379 "client-d": makeClientRecord("client-c", { version: "54.0a1" }),380 });381 let requestor = NewBookmarkRepairRequestor(mockService);382 ok(requestor._isSuitableClient(mockService.clientsEngine.remoteClient("client-a")));383 ok(!requestor._isSuitableClient(mockService.clientsEngine.remoteClient("client-b")));384 ok(!requestor._isSuitableClient(mockService.clientsEngine.remoteClient("client-c")));385 ok(requestor._isSuitableClient(mockService.clientsEngine.remoteClient("client-d")));386});387add_task(async function test_requestor_already_repairing_at_start() {388 let mockService = new MockService({ });389 let requestor = NewBookmarkRepairRequestor(mockService);390 requestor.anyClientsRepairing = () => true;391 let validationInfo = {392 problems: {393 missingChildren: [394 {parent: "x", child: "a"},395 {parent: "x", child: "b"},396 {parent: "x", child: "c"},397 ],398 orphans: [],399 },400 };401 let flowID = Utils.makeGUID();402 ok(!(await requestor.startRepairs(validationInfo, flowID)),403 "Shouldn't start repairs");404 equal(mockService._recordedEvents.length, 1);405 equal(mockService._recordedEvents[0].method, "aborted");406});407add_task(async function test_requestor_already_repairing_continue() {408 let clientB = makeClientRecord("client-b");409 let mockService = new MockService({410 "client-a": makeClientRecord("client-a"),411 "client-b": clientB,412 });413 let requestor = NewBookmarkRepairRequestor(mockService);414 let validationInfo = {415 problems: {416 missingChildren: [417 {parent: "x", child: "a"},418 {parent: "x", child: "b"},419 {parent: "x", child: "c"},420 ],421 orphans: [],422 },423 };...

Full Screen

Full Screen

auth-guard.service.spec.ts

Source:auth-guard.service.spec.ts Github

copy

Full Screen

1import { TestBed, waitForAsync } from '@angular/core/testing';2import { Router } from '@angular/router';3import { RouterTestingModule } from '@angular/router/testing';4import { EventType, OAuthService } from 'angular-oauth2-oidc';5import { MockOAuthService } from '../../../testing/mocks';6import { AuthService } from '../auth/auth.service';7class FakeComponent {}8const loginUrl = '/should-login';9describe('AuthService', () => {10 let service: AuthService;11 let mockService: MockOAuthService;12 let router: Router;13 beforeEach(() => {14 TestBed.configureTestingModule({15 imports: [RouterTestingModule.withRoutes([16 { path: 'should-login', component: FakeComponent }17 ])],18 providers: [19 AuthService,20 {provide: OAuthService, useClass: MockOAuthService}21 ]22 });23 service = TestBed.inject(AuthService);24 mockService = TestBed.inject(OAuthService) as any as MockOAuthService;25 router = TestBed.inject(Router);26 spyOn(router, 'navigateByUrl');27 });28 it('should react on OAuthService events', () => {29 spyOn(mockService, 'hasValidAccessToken');30 spyOn(mockService, 'loadUserProfile');31 mockService.emulateEvent({type: 'silently_refreshed'});32 mockService.emulateEvent({type: 'token_received'});33 expect(mockService.loadUserProfile).toHaveBeenCalled();34 expect(mockService.hasValidAccessToken).toHaveBeenCalledTimes(2);35 });36 ['session_terminated', 'session_error'].forEach(eventType => {37 it(`should react on OAuthService event ${eventType} and redirect to login`, () => {38 mockService.emulateEvent({type: eventType as EventType});39 expect(router.navigateByUrl).toHaveBeenCalledWith(loginUrl);40 });41 });42 it('should handle storage event and update isAuthenticated status', () => {43 mockService.updateTokenValidity(false);44 window.dispatchEvent(new StorageEvent('storage', {key: 'access_token'}));45 expect(router.navigateByUrl).toHaveBeenCalledWith(loginUrl);46 service.isAuthenticated$.subscribe(isAuthenticated => expect(isAuthenticated).toBe(false));47 });48 describe('runInitialLoginSequence', () => {49 it('should login via hash if token is valid', waitForAsync (() => {50 spyOn(mockService, 'tryLogin');51 spyOn(mockService, 'silentRefresh');52 mockService.updateTokenValidity(true);53 service.runInitialLoginSequence().then(() => {54 expect(mockService.tryLogin).toHaveBeenCalled();55 expect(mockService.silentRefresh).not.toHaveBeenCalled();56 });57 }));58 it('should silent login via refresh and navigate to state url when required user interaction', waitForAsync (() => {59 spyOn(mockService, 'tryLogin');60 spyOn(mockService, 'silentRefresh').and.returnValue(Promise.resolve({61 type: 'silently_refreshed',62 reason: {error: 'login_required'}63 }));64 mockService.state = '/some/url';65 service.runInitialLoginSequence().then(() => {66 expect(mockService.tryLogin).toHaveBeenCalled();67 expect(mockService.silentRefresh).toHaveBeenCalled();68 expect(router.navigateByUrl).toHaveBeenCalledWith('/some/url');69 });70 }));71 it('should silent login via refresh without redirect', waitForAsync (() => {72 spyOn(mockService, 'tryLogin');73 spyOn(mockService, 'silentRefresh');74 service.runInitialLoginSequence().then(() => {75 expect(mockService.tryLogin).toHaveBeenCalled();76 expect(mockService.silentRefresh).toHaveBeenCalled();77 expect(router.navigateByUrl).not.toHaveBeenCalled();78 });79 }));80 });...

Full Screen

Full Screen

auth.service.spec.ts

Source:auth.service.spec.ts Github

copy

Full Screen

1import { TestBed, waitForAsync } from '@angular/core/testing';2import { Router } from '@angular/router';3import { RouterTestingModule } from '@angular/router/testing';4import { EventType, OAuthService } from 'angular-oauth2-oidc';5import { MockOAuthService } from '../../../testing/mocks';6import { AuthService } from './auth.service';7class FakeComponent {}8const loginUrl = '/should-login';9describe('AuthService', () => {10 let service: AuthService;11 let mockService: MockOAuthService;12 let router: Router;13 beforeEach(() => {14 TestBed.configureTestingModule({15 imports: [RouterTestingModule.withRoutes([16 { path: 'should-login', component: FakeComponent }17 ])],18 providers: [19 AuthService,20 {provide: OAuthService, useClass: MockOAuthService}21 ]22 });23 service = TestBed.inject(AuthService);24 mockService = TestBed.inject(OAuthService) as any as MockOAuthService;25 router = TestBed.inject(Router);26 spyOn(router, 'navigateByUrl');27 });28 it('should react on OAuthService events', () => {29 spyOn(mockService, 'hasValidAccessToken');30 spyOn(mockService, 'loadUserProfile');31 mockService.emulateEvent({type: 'silently_refreshed'});32 mockService.emulateEvent({type: 'token_received'});33 expect(mockService.loadUserProfile).toHaveBeenCalled();34 expect(mockService.hasValidAccessToken).toHaveBeenCalledTimes(2);35 });36 ['session_terminated', 'session_error'].forEach(eventType => {37 it(`should react on OAuthService event ${eventType} and redirect to login`, () => {38 mockService.emulateEvent({type: eventType as EventType});39 expect(router.navigateByUrl).toHaveBeenCalledWith(loginUrl);40 });41 });42 it('should handle storage event and update isAuthenticated status', () => {43 mockService.updateTokenValidity(false);44 window.dispatchEvent(new StorageEvent('storage', {key: 'access_token'}));45 expect(router.navigateByUrl).toHaveBeenCalledWith(loginUrl);46 service.isAuthenticated$.subscribe(isAuthenticated => expect(isAuthenticated).toBe(false));47 });48 describe('runInitialLoginSequence', () => {49 it('should login via hash if token is valid', waitForAsync (() => {50 spyOn(mockService, 'tryLogin');51 spyOn(mockService, 'silentRefresh');52 mockService.updateTokenValidity(true);53 service.runInitialLoginSequence().then(() => {54 expect(mockService.tryLogin).toHaveBeenCalled();55 expect(mockService.silentRefresh).not.toHaveBeenCalled();56 });57 }));58 it('should silent login via refresh and navigate to state url when required user interaction', waitForAsync (() => {59 spyOn(mockService, 'tryLogin');60 spyOn(mockService, 'silentRefresh').and.returnValue(Promise.resolve({61 type: 'silently_refreshed',62 reason: {error: 'login_required'}63 }));64 mockService.state = '/some/url';65 service.runInitialLoginSequence().then(() => {66 expect(mockService.tryLogin).toHaveBeenCalled();67 expect(mockService.silentRefresh).toHaveBeenCalled();68 expect(router.navigateByUrl).toHaveBeenCalledWith('/some/url');69 });70 }));71 it('should silent login via refresh without redirect', waitForAsync (() => {72 spyOn(mockService, 'tryLogin');73 spyOn(mockService, 'silentRefresh');74 service.runInitialLoginSequence().then(() => {75 expect(mockService.tryLogin).toHaveBeenCalled();76 expect(mockService.silentRefresh).toHaveBeenCalled();77 expect(router.navigateByUrl).not.toHaveBeenCalled();78 });79 }));80 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockService } from 'ng-mocks';2import { MyService } from './my.service';3describe('MyService', () => {4 let service: MyService;5 beforeEach(() => {6 service = MockService(MyService);7 });8 it('should return 1', () => {9 expect(service.get()).toEqual(1);10 });11});12export class MyService {13 get() {14 return 1;15 }16}

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockService } from 'ng-mocks';2import { Service } from 'service';3const service = MockService(Service);4import { SpyObject } from 'ng-mocks';5import { Service } from 'service';6const service = SpyObject(Service);7import { createSpyObject } from 'ng-mocks';8import { Service } from 'service';9const service = createSpyObject(Service);10import { MockService } from 'ng-mocks';11import { Service } from 'service';12import { Component } from 'component';13const service = MockService(Service);14const component = new Component(service);15component.ngOnInit();16expect(service.foo).toHaveBeenCalled();17import { SpyObject } from 'ng-mocks';18import { Service } from 'service';19import { Component } from 'component';20const service = SpyObject(Service);21const component = new Component(service);22component.ngOnInit();23expect(service.foo).toHaveBeenCalled();24import { createSpyObject } from 'ng-mocks';25import { Service } from 'service';26import { Component } from 'component';27const service = createSpyObject(Service);28const component = new Component(service);29component.ngOnInit();30expect(service.foo).toHaveBeenCalled();31import { MockService } from 'ng-mocks';32import { Service } from 'service';33import { Component } from 'component';34const service = MockService(Service);35service.foo.and.returnValue(123);36const component = new Component(service);37component.ngOnInit();38expect(component.bar).toEqual(123);39import { SpyObject } from 'ng-mocks';40import { Service } from 'service';41import { Component } from 'component';

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockService } from 'ng-mocks';2import { Service } from './service';3import { TestBed } from '@angular/core/testing';4import { OtherService } from './other-service';5import { ServiceFake } from './service-fake';6describe('Test', () => {7 beforeEach(() => {8 TestBed.configureTestingModule({9 {10 useValue: MockService(Service, {11 method: () => 'fake',12 }),13 },14 {15 useValue: MockService(OtherService, {16 otherMethod: () => 'fake',17 }),18 },19 {20 useValue: MockService(ServiceFake, {21 method: () => 'fake',22 }),23 },24 });25 });26});27import { Injectable } from '@angular/core';28import { OtherService } from './other-service';29import { ServiceFake } from './service-fake';30@Injectable()31export class Service {32 constructor(33 ) {}34 method(): string {35 return this.otherService.otherMethod();36 }37}38import { Injectable } from '@angular/core';39@Injectable()40export class OtherService {41 otherMethod(): string {42 return 'other';43 }44}45import { Injectable } from '@angular/core';46@Injectable()47export class ServiceFake {48 method(): string {49 return 'other';50 }51}52import { TestBed } from '@angular/core/testing';53import { Service } from './service';54import { OtherService } from './other-service';55import { ServiceFake } from './service-fake';56describe('Service', () => {57 let service: Service;58 let otherService: OtherService;59 let serviceFake: ServiceFake;60 beforeEach(() => {61 TestBed.configureTestingModule({62 {63 useValue: MockService(Service, {64 method: () => 'fake',65 }),66 },67 {68 useValue: MockService(OtherService, {

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockService } from 'ng-mocks';2import { Service } from './service';3export function test() {4 const service = MockService(Service);5}6import { Injectable } from '@angular/core';7@Injectable()8export class Service {9 method() {10 return 'real';11 }12}13import { Injectable } from '@angular/core';14import { Service } from './service';15@Injectable()16export class ServiceMock extends Service {17 method() {18 return 'mock';19 }20}21import { test } from './test';22describe('ServiceMock', () => {23 it('should mock', () => {24 expect(test()).toEqual('mock');25 });26});27import { test } from './test';28describe('Service', () => {29 it('should real', () => {30 expect(test()).toEqual('real');31 });32});

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockService } from 'ng-mocks';2import { MyService } from './my.service';3const mockService = MockService(MyService);4const service = new MyService();5const serviceSpy = spyOn(service, 'getMyData');6describe('MyService', () => {7 it('should call my service', () => {8 mockService.getMyData.and.returnValue('test');9 expect(service.getMyData()).toEqual('test');10 expect(serviceSpy).toHaveBeenCalled();11 });12});

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