it('should pass a blog item to remove to the blogService during delete', () => {
    blogRoll.ngOnInit();
    // alerts/confirm are an awful idea (short timeframe for this demo)
    // but we can deal with the confirm message box by mocking it away,
    // and returning true to continue processing - thanks Jasmine!
    spyOn(window, 'confirm')
       .and.callFake(() => { return true; });

    // now mock the actual call to
    spyOn(blogService, 'deleteBlogEntry')
       .and.returnValue(Observable.of({ complete: true}));
    let entry = new BlogEntry(null ,null, null, 15);
    blogRoll.deleteBlogEntry(entry);

    // collaborator behavior check
    expect(window.confirm).toHaveBeenCalled();
    expect(blogService.deleteBlogEntry).toHaveBeenCalledWith(15);
  });
    beforeEach(() => {

        fixture = TestBed.createComponent(ProcessCommentsComponent);
        component = fixture.componentInstance;
        service = fixture.debugElement.injector.get(TaskListService);

        getCommentsSpy = spyOn(service, 'getComments').and.returnValue(Observable.of([
            { message: 'Test1', created: Date.now(), createdBy: {firstName: 'Admin', lastName: 'User'} },
            { message: 'Test2', created: Date.now(), createdBy: {firstName: 'Admin', lastName: 'User'} },
            { message: 'Test3', created: Date.now(), createdBy: {firstName: 'Admin', lastName: 'User'} }
        ]));

        componentHandler = jasmine.createSpyObj('componentHandler', [
            'upgradeAllRegistered',
            'upgradeElement'
        ]);
        window['componentHandler'] = componentHandler;
    });
                fakeAsync((service: Register, mockTranslate: MockLanguageService) => {
                    spyOn(service, 'save').and.returnValue(Observable.of({}));
                    comp.registerAccount.password = comp.confirmPassword = 'password';

                    comp.register();
                    tick();

                    expect(service.save).toHaveBeenCalledWith({
                        password: 'password',
                        langKey: 'fr'
                    });
                    expect(comp.success).toEqual(true);
                    expect(comp.registerAccount.langKey).toEqual('fr');
                    expect(mockTranslate.getCurrentSpy).toHaveBeenCalled();
                    expect(comp.errorUserExists).toBeNull();
                    expect(comp.errorEmailExists).toBeNull();
                    expect(comp.error).toBeNull();
                })
                fakeAsync((service: Register) => {
                    spyOn(service, 'save').and.returnValue(Observable.of({}));
                    comp.registerAccount.password = comp.confirmPassword = 'password';

                    comp.register();
                    tick();

                    expect(service.save).toHaveBeenCalledWith({
                        password: 'password',
                        langKey: 'en'
                    });
                    expect(comp.success).toEqual(true);
                    expect(comp.registerAccount.langKey).toEqual('en');
                    
                    expect(comp.errorUserExists).toBeNull();
                    expect(comp.errorEmailExists).toBeNull();
                    expect(comp.error).toBeNull();
                })
                fakeAsync((mockPrincipal: MockPrincipal, service: SessionsService) => {
                    mockPrincipal.spy('identity').and.returnValue(Promise.resolve({
                        id: 'fuzzer'
                    }));
                    spyOn(service, 'findAll').and.returnValue(Observable.of(sessions));

                    comp.ngOnInit();
                    tick();

                    expect(mockPrincipal.identitySpy).toHaveBeenCalled();
                    expect(service.findAll).toHaveBeenCalled();
                    expect(comp.success).toBeUndefined();
                    expect(comp.error).toBeUndefined();
                    expect(comp.account).toEqual({
                        id: 'fuzzer'
                    });
                    expect(comp.sessions).toEqual(sessions);
                })
Example #6
0
 // retry pattern    
 constructor7() {
     var counter = 0;
     
     var ajaxCall = Observable.of('url')
         .delay(2000)
         .flatMap( () => {
             if (counter++ < 2) {
                 console.log("counter =", counter);                    
                 return Observable.throw(new Error("Request failed"));
             }
             return Observable.of([1,2,3]);
         });
     ajaxCall
         .retry(3)
         .subscribe(
         x => console.log(x),
         e => console.error(e)
     );        
 }
	getUser():Observable<User>{

		if(this._user == undefined)
		{

			let headers = new Headers({ 'Content-Type': 'application/json' });
			let options = new RequestOptions({ headers: headers });

			this.applyTokenToHeader(options);

			return this.http.post(UserService.API + "/auth/verify",{},options).map(this.extractData).map((res) => {
				this._user = res;
				return this._user;
			});
		
		}

		return Observable.of<User>(this._user);
	}
Example #8
0
 login(username: String) {
     this.http.post('http://localhost:8080/login', JSON.stringify({
             login: username
         }), {
             headers: new Headers({
                 'Content-Type': 'application/json'
             })
         })
         .map(res => res.json())
         .subscribe(
             res => this.token = res.token,
             err => console.log("Service is unavailable")
         );
     if(this.token == "failed") {
         this.token = undefined;
         return Observable.throw('authentication failure');
     }
     return Observable.of(this.token);
 }
    it('should return an observable', () => {
        const spy = jest.fn();

        const subt = {
            process(o) {
                return Observable.of(o);
            }
        }

        subt.process = jest.fn(subt.process);

        const t = new MapTransformer(subt);

        t.process(Observable.from([1]), 2)
            .subscribe(spy, null, () => {
                expect(spy.mock.calls.length).toBe(1);
                expect((subt.process as any).mock.calls.length).toBe(1);
            });
    });
        it('should load the thumbnail preview of a pdf', (done) => {
            let blob = createFakePdfBlob();
            spyOn(serviceForm, 'getContentThumbnailUrl').and.returnValue(Observable.of(blob));

            component.thumbnailLoaded.subscribe((res) => {
                fixture.detectChanges();
                expect(res).toBeDefined();
                expect(res.changingThisBreaksApplicationSecurity).toBeDefined();
                expect(res.changingThisBreaksApplicationSecurity).toContain('blob');
                fixture.whenStable()
                    .then(() => {
                        let thumbnailPreview: any = element.querySelector('#thumbnailPreview');
                        expect(thumbnailPreview.src).toContain('blob');
                    });
                done();
            });

            let contentId = 1;
            let change = new SimpleChange(null, contentId, true);
            component.ngOnChanges({'id': change});

            jasmine.Ajax.requests.mostRecent().respondWith({
                status: 200,
                contentType: 'json',
                responseText: {
                    id: 4004,
                    name: 'FakeBlob.pdf',
                    created: 1490354907883,
                    createdBy: {
                        id: 2,
                        firstName: 'dasdas', 'lastName': 'dasads', 'email': 'administrator@admin.com'
                    },
                    relatedContent: false,
                    contentAvailable: true,
                    link: false,
                    mimeType: 'application/pdf',
                    simpleType: 'pdf',
                    previewStatus: 'created',
                    thumbnailStatus: 'created'
                }
            });
        });
Example #11
0
        it("should resolve when any of the observables from the items resolve", () => {
            var obj1 = new ReactiveObject();
            var obj2 = new ReactiveObject();
            var obj1Subject = new Subject<string>();
            var obj2Subject = new Subject<string>();
            var arr = ReactiveArray.of(obj1, obj2);

            obj1.set("observable", obj1Subject);
            obj2.set("observable", obj2Subject);

            var events: string[] = [];
            arr.whenAnyItemObservable<string>("observable").subscribe(e => events.push(e));
            expect(events).to.eql([]);
            obj1Subject.next("First");
            expect(events).to.eql(["First"]);
            obj2Subject.next("Second");
            expect(events).to.eql(["First", "Second"]);
            obj1.set("observable", Observable.of("Other"));
            expect(events).to.eql(["First", "Second", "Other"]);
        });
 getData() {
     return  Observable.of ([
         {
             name: '2014년',
             accident: [{
                 weather: "양호",
                 name: '테스트1',
                 death: 100
             }]   
         },
         {
             name: '2014년 테스트1',
             accident: [{
                 weather: "태풍주의보",
                 name: '테스트2',
                 death: 10
             }]   
         }
     ]);  
 }
 descriptor.value = function(...args: any[]) {
     let key = getCacheKey(functionName, propertyKey, args);
     let cache = cachedData[key];
     if (cache && cache.data) {
         return Observable.of(cache.data);
     } else if (cache && cache.observable){
         return cache.observable;
     } else {
         cache = {
             observable: originalMethod.apply(this, args)
             .map(r => {
                 delete cache.observable;
                 cache.data = r;
                 return cache.data;
             }).share()
         };
         cachedData[key] = cache;
         return cache.observable;
     }
 };
    it('should fetch and parse form by task id', (done) => {
        spyOn(formService, 'getTask').and.returnValue(Observable.of({}));
        spyOn(formService, 'getTaskForm').and.callFake((currentTaskId) => {
            return Observable.create(observer => {
                observer.next({ taskId: currentTaskId });
                observer.complete();
            });
        });

        const taskId = '456';
        formComponent.formLoaded.subscribe(() => {
            expect(formService.getTaskForm).toHaveBeenCalledWith(taskId);
            expect(formComponent.form).toBeDefined();
            expect(formComponent.form.taskId).toBe(taskId);
            done();
        });

        expect(formComponent.form).toBeUndefined();
        formComponent.getFormByTaskId(taskId);
    });
	allQuestionsData$(): Observable<any> {
		return Observable.of({
			"-KLMInMzgKpxJeOxqieT": {
				question: "Kde sa tento rok (2016) konajú olympijské hry?",
				answer1: "Atény",
				answer2: "Tokyo",
				answer3: "Rio de Janeiro",
				answer4: "Londýn",
				timesFailed: 0
			},
			"-KLMTxMpSzlJwz4aCfLB": {
				question: "V ktorých športoch nemáme ani sme nikdy nemali reprezentantov?",
				answer1: "tenis",
				answer2: "kanoistika",
				answer3: "golf",
				answer4: "športová streľba",
				timesFailed: 0
			}
		});
	}
    getList(name:string):Observable<List> {
        let obs$: Observable<List>;

        if (this._lists.hasOwnProperty(name)) {
            obs$ = Observable.of(this._lists[name]);
        } else {
            let dsList = this._deepstream.record.getList(name);
            this._lists[name] = new List(this._deepstream, dsList);

            obs$ = Observable.fromEvent(dsList, "ready")
                .map(r => this._lists[name]);
        }

        (obs$ as any).getEntries = () => {
            return obs$.flatMap(list => {
                return list.getEntries();
            });
        };
        return obs$;
    }
  logout() {
    /*
     * If we had a login api, we would have done something like this

    return this.http.get(this.config.serverUrl + '/auth/logout', {
      headers: new Headers({
        'x-security-token': this.token
      })
    })
    .map((res : any) => {
      this.token = undefined;
      localStorage.removeItem('token');
    });
     */

    this.token = undefined;
    localStorage.removeItem('token');

    return Observable.of(true);
  }
Example #18
0
    public login(requestData: Object = {}): Observable<boolean> | boolean {
        let router: Router = this.router;
        let obs;
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');


        try {
            obs = this.http.post(apiUrl.login,
                JSON.stringify(requestData),
                { headers })
                .map(this.success)
                .catch(this.error);

        } catch (err) {
            obs = Observable.of(false);
        }

        return obs
            .map(this.success);
    }
    beforeEach(() => {

        fixture = TestBed.createComponent(ActivitiComments);
        component = fixture.componentInstance;
        service = fixture.debugElement.injector.get(ActivitiTaskListService);

        getCommentsSpy = spyOn(service, 'getTaskComments').and.returnValue(Observable.of([{
            message: 'Test1'
        }, {
            message: 'Test2'
        }, {
            message: 'Test3'
        }]));
        addCommentSpy = spyOn(service, 'addTaskComment').and.returnValue(Observable.of({id: 123, message: 'Test'}));

        componentHandler = jasmine.createSpyObj('componentHandler', [
            'upgradeAllRegistered',
            'upgradeElement'
        ]);
        window['componentHandler'] = componentHandler;
    });
  private getDailyMealProviders(): Observable<MealProvider> {
    var providersByUrl:{[key:string]:MealProvider} = {};
    var providerXPaths:Observable<XpathResolutionResult>[] = [];

    this.getCachedMealProviders()
    .forEach((provider:MealProvider)=>{
      providersByUrl[provider.dailyMealUrl] = provider;
      var xpaths:string[] = [];
      for (var key in provider.dailyMealQueryXPathByMealSet) {
        xpaths.push(provider.mealSetQueryXPath[key]);
        xpaths = [...xpaths, ...provider.dailyMealQueryXPathByMealSet[key], provider.mealSetPriceQueryXPathByMealSet[key]];
      }
      providerXPaths.push(this.xpathService.resolveXPaths(provider.dailyMealUrl, ...xpaths));
    });

    return Observable.of(providerXPaths)
    .flatMap((providerXPath)=>providerXPath)
    .mergeAll()
    .map((providerXPath:XpathResolutionResult)=>{
      let provider = providersByUrl[providerXPath.url];
      let xpaths = providerXPath.xpathResult;
      let mealSets:MealSet[] = [];

      for (var mealSetKey in provider.mealSetQueryXPath) {
        let meals: Meal[] = [];
        for (var mealXPath of provider.dailyMealQueryXPathByMealSet[mealSetKey]) {
          meals.push(new Meal(xpaths[mealXPath].trim()));
        }
        let price: Price = null;
        if (provider.mealSetPriceQueryXPathByMealSet[mealSetKey]) {
          price = Price.fromString(xpaths[provider.mealSetPriceQueryXPathByMealSet[mealSetKey]]);
        }
        let mealSet: MealSet = new MealSet(xpaths[provider.mealSetQueryXPath[mealSetKey]], meals, price, provider);
        mealSets.push(mealSet);
      }
      provider.mealSets = mealSets;
      provider.distance = this.mapService.calculateDistance(provider.location, this.mapService.getCachedHome().location);
      return provider;
    });
  }
describe('JobSearchListComponent', () => {
    const mockStore = jasmine.createSpyObj('mockStore', ['select', 'dispatch']);
    mockStore.select.and.returnValue(Observable.of([]));

    let component: JobSearchListComponent;
    let fixture: ComponentFixture<JobSearchListComponent>;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [JobroomTestModule],
            declarations: [JobSearchListComponent],
            providers: [
                { provide: Store, useValue: mockStore },
            ]
        })
            .overrideTemplate(JobSearchListComponent, '')
            .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(JobSearchListComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should be created', () => {
        expect(component).toBeTruthy();
    });

    describe('onScroll', () => {
        it('should dispatch an LoadNextPageAction', () => {

            // WHEN
            component.onScroll({});

            // THEN
            expect(mockStore.dispatch).toHaveBeenCalledWith(new LoadNextPageAction());
        });
    });
});
    beforeEach(() => {
        ScenarioService = jasmine.createSpyObj('ScenarioService', ['delete', 'update']);
        Router = jasmine.createSpyObj('Router', ['navigate']);
        ScenarioStatusService = {
            stream: new Subject()
        };
        ActivatedRoute = {
            data: Observable.of({scenarioList: mockScenarios})
        };
        DialogService = jasmine.createSpyObj('DialogService', ['confirm']);
        ViewContainerRef = {};

        spyOn(ActivatedRoute.data, 'subscribe').and.callThrough();
        sut = new ScenarioListComponent(
            ScenarioService,
            Router,
            ScenarioStatusService,
            ActivatedRoute,
            DialogService,
            ViewContainerRef
        );
    });
Example #23
0
	saveModel(model: ServiceModel): Observable<ServiceModel> {

		if (!model) {
			return Observable.of(model);
		}

		let body = JSON.stringify(model);
		let headers = new Headers({
			'Content-Type': 'application/json'
		});

		return this.http.post('/api/service', body, { headers: headers }).map(
			res => {
				if (res.ok) {
					return res.json();
				}
				else {
					return false;
				}
			}
		);
	}
 it('should difine title and [custom-action-buttons]', async(() => {
     getStartFormSpy.and.returnValue(Observable.of(startMockFormWithTab));
     component.processDefinitionId = exampleId1;
     component.showOutcomeButtons = true;
     component.showRefreshButton = true;
     component.ngOnChanges({ processDefinitionId: new SimpleChange(exampleId1, exampleId2, true) });
     fixture.whenStable().then(() => {
         fixture.detectChanges();
         const titleIcon = fixture.debugElement.nativeElement.querySelector('md-card-title>md-icon');
         const titleElement = fixture.debugElement.nativeElement.querySelector('md-card-title>h2');
         const actionButtons = fixture.debugElement.nativeElement.querySelectorAll('.mat-button');
         expect(titleIcon).toBeDefined();
         expect(titleElement).toBeDefined();
         expect(actionButtons.length).toBe(4);
         expect(actionButtons[0].innerText).toBe('Save');
         expect(actionButtons[0].disabled).toBeFalsy();
         expect(actionButtons[1].innerText).toBe('Approve');
         expect(actionButtons[1].disabled).toBeTruthy();
         expect(actionButtons[2].innerText).toBe('Complete');
         expect(actionButtons[2].disabled).toBeTruthy();
     });
 }));
 it('should be able to display a dropDown Widget from a process definition', () => {
     getStartFormSpy.and.returnValue(Observable.of(startFormDropdownDefinitionMock));
     component.processDefinitionId = exampleId1;
     component.showOutcomeButtons = true;
     component.ngOnChanges({ processDefinitionId: new SimpleChange(exampleId1, exampleId2, true) });
     fixture.detectChanges();
     fixture.whenStable().then(() => {
         fixture.detectChanges();
         const formFields = component.form.getFormFields();
         const labelField = formFields.find(field => field.id === 'mockTypeDropDown');
         const dropDownWidget = fixture.debugElement.nativeElement.querySelector('dropdown-widget');
         const selectElement = fixture.debugElement.nativeElement.querySelector('.adf-dropdown-widget>md-select .mat-select-trigger');
         selectElement.click();
         expect(selectElement).toBeDefined();
         expect(dropDownWidget).toBeDefined();
         expect(selectElement.innerText).toBe('Choose one...');
         expect(labelField.type).toBe('dropdown');
         expect(labelField.options[0].name).toBe('Chooseone...');
         expect(labelField.options[1].name).toBe('Option-1');
         expect(labelField.options[2].name).toBe('Option-2');
     });
 });
Example #26
0
	saveDepModel(model: DepartmentModel): Observable<DepartmentModel> {

		if (!model) {
			return Observable.of(model);
		}

		let body = JSON.stringify(model);
		let headers = new Headers({
			'Content-Type': 'application/json'
		});

		return this.http.post('/api/department', body, { headers: headers }).map(
			res => {
				if (res.status == 200) {
					return res.json();
				}
				else {
					return false;
				}
			}
		);
	}
            it('should show the hidden field when the visibility condition change to true', () => {
                taskSpy = spyOn(service, 'getTask').and.returnValue(Observable.of({}));
                formDefinitionSpy = spyOn(service, 'getTaskForm').and.returnValue(Observable.of(formDefVisibilitiFieldDependsOnNextOne));

                let change = new SimpleChange(null, 1, true);
                component.ngOnChanges({ 'taskId': change });
                fixture.detectChanges();

                let firstEl = fixture.debugElement.query(By.css('#country'));
                expect(firstEl).toBeNull();

                const secondEl = fixture.debugElement.query(By.css('#name'));
                expect(secondEl).not.toBeNull();

                let el = secondEl.nativeElement;

                el.value = 'italy';
                el.dispatchEvent(new Event('input'));
                fixture.detectChanges();

                firstEl = fixture.debugElement.query(By.css('#country'));
                expect(firstEl).not.toBeNull();
            });
 it('should disply start form with fields ', async(() => {
     getStartFormSpy.and.returnValue(Observable.of(startMockForm));
     component.processDefinitionId = exampleId1;
     component.showOutcomeButtons = true;
     component.ngOnChanges({ processDefinitionId: new SimpleChange(exampleId1, exampleId2, true) });
     fixture.whenStable().then(() => {
         fixture.detectChanges();
         const formFieldsWidget = fixture.debugElement.nativeElement.querySelector('form-field');
         const inputElement = fixture.debugElement.nativeElement.querySelector('.adf-input');
         const inputLabelElement = fixture.debugElement.nativeElement.querySelector('.mat-input-infix > .adf-label');
         const dateElement = fixture.debugElement.nativeElement.querySelector('#billdate');
         const dateLabelElement = fixture.debugElement.nativeElement.querySelector('#data-widget .mat-input-infix> .adf-label');
         const selectElement = fixture.debugElement.nativeElement.querySelector('#claimtype');
         const selectLabelElement = fixture.debugElement.nativeElement.querySelector('.adf-dropdown-widget > .adf-label');
         expect(formFieldsWidget).toBeDefined();
         expect(inputElement).toBeDefined();
         expect(dateElement).toBeDefined();
         expect(selectElement).toBeDefined();
         expect(inputLabelElement.innerText).toBe('ClientName*');
         expect(dateLabelElement.innerText).toBe('BillDate (D-M-YYYY)');
         expect(selectLabelElement.innerText).toBe('ClaimType');
     });
 }));
    // TODO: real auth service returns Observable<string>
    login(username: string, password: string): Observable<boolean> {
        if (username === 'fake-username' && password === 'fake-password') {
            return Observable.of(true);
        }

        if (username === 'fake-username-CORS-error' && password === 'fake-password') {
            return Observable.throw({
                error: {
                    crossDomain: true,
                    message: 'ERROR: the network is offline, Origin is not allowed by Access-Control-Allow-Origin'
                }
            });
        }

        if (username === 'fake-username-CSRF-error' && password === 'fake-password') {
            return Observable.throw({message: 'ERROR: Invalid CSRF-token', status: 403});
        }

        if (username === 'fake-username-ECM-access-error' && password === 'fake-password') {
            return Observable.throw({message: 'ERROR: 00170728 Access Denied.  The system is currently in read-only mode', status: 403});
        }

        return Observable.throw('Fake server error');
    }
 public getPosition():Observable<Coordinates> {
   if (navigator.geolocation) {
     return Observable.create(
         function (observer:Observer<any>) {
           let callback = function (position:any) {
             let coords = new Coordinates(
                 position.coords.longitude,
                 position.coords.latitude);
             return observer.next(coords);
           };
           let errorCallback = function (error:any) {
             alert('Fehler: ' + error + '\n' + error.code + '\n' + error.message);
             console.log(error);
           };
           navigator.geolocation.getCurrentPosition(callback, errorCallback,
               {
                 enableHighAccuracy: true,
                 timeout: 5000,
                 maximumAge: 60000
               });
         });
   }
   return Observable.of(new Coordinates(0, 0));
 }