cordova.fileTransfer not updating page template Ionic2+Cordova - ionic2

I have created an Ionic2 App using cordova FileTransferplugin, i am downloading remote server file.
Everything is working perfectly, but when I try to update template while fileTransfer.OnProgress event, the template is not updating the % downloaded.
Pleas see this video for my problem.
Ionic_youtube_link
My Code is, logic is in downloadFile function
import {Component, AfterViewInit, ViewChild} from '#angular/core';
import {NavController, NavParams, ViewController, Nav} from 'ionic-angular';
import {Page, Platform} from 'ionic-angular';
import {File, Device, Cordova, Transfer} from 'ionic-native';
import { SafeResourceUrl, DomSanitizationService } from '#angular/platform-browser';
#Component({
templateUrl: 'build/pages/video-download-modal/video-download-modal.html',
providers: [File, Transfer]
})
export class VideoDownloadModal {
selectedItem: any;
#ViewChild(Nav) nav: Nav;
videoPathUrl: string;
isPlatformReady: boolean;
platformName: string;
directoryName: string = "socialAppDir";
totalVideoSize:number;
totalDownloaded:number;
totalPercent:string = "0%";
constructor(public navCtrl: NavController, navParams: NavParams, private _viewController: ViewController, platform: Platform, private transfer:Transfer) {
// If we navigated to this page, we will have an item available as a nav param
if (platform.is('core')) {//if on dekstop
console.log('dektop');
} else {
this.videoPathUrl = navParams.get('videoPath');
console.log(this.videoPathUrl);
platform.ready().then((readySource) => {
this.isPlatformReady = true;
console.log('ready 1234');
const fs: string = cordova.file.externalRootDirectory;
console.log(cordova.file.dataDirectory);
this.platformName = Device.device.platform;
File.checkDir(cordova.file.externalDataDirectory, this.directoryName).then(() => {
console.log('directory exists');
this.downloadFile();
}, (error) => {
console.log('directory not exists');
this.createDirectory();
})
})
}
}
dismiss() {
let data = { 'foo': 'bar' };
this._viewController.dismiss(data);
}
createDirectory():void{
File.createDir(cordova.file.externalDataDirectory, this.directoryName, true).then(() => {
console.log("created externalDataDirectory");
this.downloadFile();
},(error) => {
console.log('some error happen')
})
}
downloadFile = () => {
console.log(this);
let fileName: string = this.videoPathUrl.split("/").pop();
let targetPath = cordova.file.externalDataDirectory + this.directoryName + "/" + fileName;
console.log(targetPath);
this.transfer.download(this.videoPathUrl, targetPath, true, {}).then(() => {
console.log('video downloaded')
}, (error) => {
console.log(error)
})
this.transfer.onProgress((progress) => {
console.log(this);
this.totalVideoSize = progress.total;
this.totalDownloaded = progress.loaded;
this.totalPercent = ((progress.loaded / progress.total) * 100).toString();
console.log(this.totalPercent);
})
}
ionViewDidEnter() {
console.log("enter login1");
}
}
And HTML is
<ion-content>
<div id="modalContainer" class="abd">
<ion-spinner></ion-spinner>
<br />
{{**totalPercent**}}
<br />
<button dnager block (click)="dismiss()">Exit</button>
</div>
</ion-content>
The totalPercent value either has 0 or 100.But not updating.
Please help.

This is because the totalPercent of this inside the handler was set to the global Window object instead of the object itself.
I have finally got it to work
import { NgZone } from '#angular/core';
fileTransfer.onProgress((progressEvent: ProgressEvent) => {
this.ngZone.run(() => {
if (progressEvent.lengthComputable) {
let lp = progressEvent.loaded / progressEvent.total * 100;
this.loadingPercent = Math.round(lp * 100) / 100;
}
});
})

Related

How to provide NgControl when testing custom field control components?

I have a simple custom control as below. Everything is working but the unit test is failing. How can I unit test this custom control? How can I pass a valid NgControl directive?
I have tried using providers:
[
{
provide: NgControl,
useValue: new FormGroup()
}
]
but I still get the same error.
core-edi.component.ts
import { Component, OnInit, Input, ViewChild, ElementRef, Self, Optional, forwardRef } from '#angular/core';
import {
ControlValueAccessor, NG_VALUE_ACCESSOR, Validator, AbstractControl,
ValidatorFn, Validators, NG_VALIDATORS, NgControl, NgForm
} from '#angular/forms';
import { Placeholder } from '#angular/compiler/src/i18n/i18n_ast';
#Component({
selector: 'app-core-edi',
templateUrl: './core-edi.component.html',
styleUrls: ['./core-edi.component.css'],
})
export class CoreEdiComponent implements ControlValueAccessor, Validator, OnInit {
#ViewChild('input') input: ElementRef;
disabled;
#Input() type = 'text';
#Input() isRequired: boolean = false;
#Input() pattern: string = null;
#Input() label: string = null;
#Input() placeholder: string;
#Input() errorMsg: string;
#Input() min: number;
#Input() minLength: number;
myhint: string = '10 digit number';
constructor(#Self() public controlDir: NgControl) {
this.controlDir.valueAccessor = this;
}
ngOnInit() {
const control = this.controlDir.control;
const validators: ValidatorFn[] = control.validator ? [control.validator] : [];
if (this.isRequired) {
validators.push(Validators.required);
}
if (this.pattern) {
validators.push(Validators.pattern(this.pattern));
}
if (this.min) {
validators.push(Validators.min(this.min));
}
control.setValidators(validators);
control.updateValueAndValidity();
this.placeholder = this.placeholder + (this.isRequired ? '*' : '');
}
onChange(event) {
}
onTouched() {
}
writeValue(obj: any): void {
this.input.nativeElement.value = obj;
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
setDisabledState?(isDisabled: boolean): void {
this.disabled = isDisabled;
}
validate(c: AbstractControl): { [key: string]: any; } {
const validators: ValidatorFn[] = [];
if (this.isRequired) {
validators.push(Validators.required);
}
if (this.pattern) {
validators.push(Validators.pattern(this.pattern));
}
if (this.min) {
validators.push(Validators.min(this.min));
}
return validators;
}
core-edi.component.html
<div class="form-label-group" fxLayout="column" fxLayoutGap="5px">
<mat-form-field class="edi-field-width">
<input matInput class="form-control"
[type]="type" #input
(input)="onChange($event.target.value)"
(blur)="onTouched()"
[disabled]="disabled"
[placeholder]="placeholder"
[min]="1111111111"
[minLength] = 10
(keyup)="mykeyup()">
<mat-hint>Hint: {{ myhint }}</mat-hint>
</mat-form-field>
<span class="error"
*ngIf="controlDir && !controlDir.control.valid
&& controlDir.control.touched">{{errorMsg}}</span>
</div>
core-edi.component.spec.ts
import { async, ComponentFixture, TestBed } from '#angular/core/testing';
import { CoreEdiComponent } from './core-edi.component';
import { FormsModule, ReactiveFormsModule, FormControl, NgControl, FormControlDirective } from '#angular/forms';
import { MaterialModule } from 'src/app/material/material.module';
fdescribe('CoreEdiComponent', () => {
let component: CoreEdiComponent;
let fixture: ComponentFixture<CoreEdiComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ CoreEdiComponent ],
imports: [
FormsModule,
ReactiveFormsModule,
MaterialModule
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CoreEdiComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
No provider for NgControl ("[ERROR ->]<app-core-edi></app-core-edi>"): #0:0
at syntaxError (./node_modules/#angular/compiler/fesm5/compiler.js?:1275:17)
at TemplateParser.parse (./node_modules/#angular/compiler/fesm5/compiler.js?:15084:19)
at JitCompiler._parseTemplate (./node_modules/#angular/compiler/fesm5/compiler.js?:24272:37)
at JitCompiler._compileTemplate (./node_modules/#angular/compiler/fesm5/compiler.js?:24259:23)
at eval (./node_modules/#angular/compiler/fesm5/compiler.js?:24202:62)
at Set.forEach (<anonymous>)
at JitCompiler._compileComponents (./node_modules/#angular/compiler/fesm5/compiler.js?:24202:19)
at eval (./node_modules/#angular/compiler/fesm5/compiler.js?:24120:19)
at Object.then (./node_modules/#angular/compiler/fesm5/compiler.js?:1266:77)
at JitCompiler._compileModuleAndAllComponents (./node_modules/#angular/compiler/fesm5/compiler.js?:24118:26)
Expected undefined to be truthy.
at UserContext.eval (./src/app/core/core-edi/core-edi.component.spec.ts?:30:27)
at ZoneDelegate.invoke (./node_modules/zone.js/dist/zone.js?:390:26)
at ProxyZoneSpec.onInvoke (./node_modules/zone.js/dist/zone-testing.js?:288:39)
I have not been through understanding how to unit test in angular yet, but maybe its in the app.module that you need to add like the ReactiveFormsModule
The answer to this helped me out
Why do I get this Template parse errors in Angular
Just my 2cents

Angular View does't refresh on array push

I am very new to ionic and angular.
Anyway, I am trying to following an tutorial to create a notes app using ionic4 https://www.joshmorony.com/building-a-notepad-application-from-scratch-with-ionic/.
So, I follow the instruction. Everything is ok except that the view doesn't updated when I add new note. The code is as follow:
Note services:
import { Injectable } from '#angular/core';
import { Storage } from '#ionic/storage';
import { Note } from '../interfaces/note';
#Injectable({
providedIn: 'root'
})
export class NotesService {
public notes: Note[] = [];
public loaded: boolean = false;
constructor(private storage: Storage) {
}
load(): Promise<boolean> {
// Return a promise so that we know when this operation has completed
return new Promise((resolve) => {
// Get the notes that were saved into storage
this.storage.get('notes').then((notes) => {
// Only set this.notes to the returned value if there were values stored
if (notes != null) {
this.notes = notes;
}
// This allows us to check if the data has been loaded in or not
this.loaded = true;
resolve(true);
});
});
}
save(): void {
// Save the current array of notes to storage
this.storage.set('notes', this.notes);
}
getNote(id): Note {
// Return the note that has an id matching the id passed in
return this.notes.find(note => note.id === id);
}
createNote(title): Promise<boolean> {
return new Promise((resolve) => {
// Create a unique id that is one larger than the current largest id
let id = Math.max(...this.notes.map(note => parseInt(note.id)), 0) + 1;
this.notes.push({
id: id.toString(),
title: title,
content: ''
});
this.save();
console.log('Service Log ' + this.notes);
resolve(true);
});
}
}
The HTML code:
<ion-header>
<ion-toolbar color="primary">
<ion-title>Notes</ion-title>
<ion-buttons slot="end">
<ion-button (click)="addNote()">
<ion-icon slot="icon-only" name="clipboard"></ion-icon>
</ion-button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<ion-item button detail *ngFor="let note of notesService.notes" [href]="'/notes/' + note.id" routerDirection="forward">
<ion-label>{{ note.title }}</ion-label>
</ion-item>
</ion-list>
</ion-content>
I've followed the same tutorial and got the same issue. The issue is because of something very interesting and powerful called Zones.
The idea is that you'd need to let Angular know that the array with the notes has changed, by doing something like this:
// Angular
import { Component, NgZone } from '#angular/core';
// Ionic
import { NavController, AlertController } from '#ionic/angular';
// Services
import { NotesService } from '../services/notes.service';
import { AlertOptions } from '#ionic/core';
#Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
constructor(
private ngZone: NgZone, // Add this in the constructor
private navCtrl: NavController,
private alertCtrl: AlertController,
private notesService: NotesService,
) { }
ngOnInit() {
this.notesService.load();
}
addNote() {
const alertOptions: AlertOptions = {
header: 'New Note',
message: 'What should the title of this note be?',
inputs: [
{
type: 'text',
name: 'title'
}
],
buttons: [
{
text: 'Cancel'
},
{
text: 'Save',
handler: (data) => {
// Create the note inside a Zone so that Angular knows
// that something has changed and the view should be updated
this.ngZone.run(() => {
this.notesService.createNote(data.title);
});
}
}
]
};
this.alertCtrl
.create(alertOptions)
.then((alert) => {
alert.present();
});
}
}

ionic 2 Side menu and log out and back key navigation

I am trying to achieve a log out functionality. I am using FB authentication. My problem here is after I do a logout successfully(This happens from the Side menu ) I return to the Login Screen. But now if I tap the device's back button it is taking me to the homepage(. Any idea how to prevent this ?
This is my app.component.ts
import { Component, ViewChild } from '#angular/core';
import { Platform, Nav, AlertController } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { LoginPage } from '../pages/login/login';
import { NativeStorage } from '#ionic-native/native-storage';
import { TabsPage } from '../pages/tabs/tabs';
import { Facebook } from 'ionic-native';
#Component({
templateUrl: 'app.html',
})
export class MyApp {
#ViewChild(Nav) nav: Nav;
rootPage: any = LoginPage;
constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, private nativeStorage: NativeStorage, private alertCtrl: AlertController) {
platform.ready().then(() => platform.ready().then(() => {
this.nativeStorage.getItem("userId").then((data) => {
console.log(data.userExists);
this.rootPage = TabsPage;
this.nav.push(TabsPage);
}, (error) => {
console.log("No data in storage");
this.nav.push(LoginPage);
})
statusBar.styleDefault();
splashScreen.hide();
})
)
}
presentConfirm() {
let alert = this.alertCtrl.create({
title: "Confirm Logout",
message: "Do you really really want to quit this awesome app?",
buttons: [{
text: 'Nah! Just Kidding!', role: 'cancel', handler: () => {
}
},
{
text: "Ok",
handler: () => {
this.nativeStorage.clear();
this.nav.push(LoginPage);
this.rootPage = LoginPage;
Facebook.logout().then((response) => {
}, (error) => {
})
}
}]
});
alert.present();
}
}
This is my login page. Login.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Facebook } from 'ionic-native';
import { NativeStorage } from '#ionic-native/native-storage';
import { TabsPage } from '../tabs/tabs'
#Component({
selector: 'login-home',
templateUrl: 'login.html'
})
export class LoginPage {
constructor(public navCtrl: NavController, private nativeStorage: NativeStorage) {
}
FBLogin() {
//this.navCtrl.push(TabsPage); - To be used on browser environment
Facebook.login(['email']).then((response) => {
Facebook.getLoginStatus().then((response) => {
if (response.status == 'connected') {
this.navCtrl.push(TabsPage); // - to be used on device
console.log("Setting Storage")
this.nativeStorage.setItem("userId", { userExists: true });
Facebook.api('/' + response.authResponse.userID + '?fields=id,name,gender', []).then((response) => {
}, (error) => {
alert(error)
})
}
else
alert("Not Logged in");
})
}, (error) => {
console.log((error));
})
}
}
This is my Menu
<ion-menu swipeEnabled="false" side="right" [content]="content">
<ion-toolbar>
<ion-title>Menu</ion-title>
</ion-toolbar>
<ion-content>
<ion-list>
<p> </p>
<button menuClose padding-top ion-item> Test 1 </button>
<button menuClose ion-item> Test 2 </button>
<button menuClose ion-item (click)="presentConfirm()"><ion-icon name="power"></ion-icon> Logout </button>
</ion-list>
</ion-content>
</ion-menu>
<ion-nav id="nav" [root]="rootPage" #content swipe-back-enabled="false"></ion-nav>
Your issue is you are doing:
this.nav.push(LoginPage);
in your logout handler.
This means LoginPage is added on top of your old navigation stack. You need to set a new stack and set LoginPage as root.
Do :
this.nav.setRoot(LoginPage);

How to write the post method in ionic?

I am new to the ionic framework,I had written the post call, I don't know exactly the post method.When i entered the submit button in forgot password page,if the user is already registered then should display the next page else it should display the alert message.
Below is my code:
import { Component } from '#angular/core';
import { configurator } from '../../providers/configurator';
import { NavController } from 'ionic-angular';
// import { LoginPage } from '../login/login';
import { persistence } from '../persistence/persistence';
#Component({
templateUrl: 'home.html'
})
export class home {
public loginId = "";
constructor(public navCtrl: NavController) {
}
generateOTP(newstate) {
console.log("invoking generateOTP FN");
var _this = this;
this.login.generateOTP(this.loginId, function(result,data){
if(result == '1') {
alert(data);
var a = document.createElement('a');
a.href="OTP page";
}
else {
//this.showRePasswd = this.showRePasswd;
alert(data);
}
})
}
}
This is my ionic-page:enter image description here
Can anyone help me!!!
my post belowed in IONIC2
import { Http, Response } from '#angular/http';
constructor(public navCtrl: NavController, private http: Http) { }
this.http.post(`${POST_URL}/log/add`, JSON.stringify(this.currentLocation), {headers})
.toPromise()
.then((response) => {
if (response.status !== 201) {
this.trace.error('log','postLog',`error response: ${response.status}`);
}
})
.catch(error => {
this.trace.error('log','postLog',`err post log:${error}`);
});

Angular 2 Testing Component Gives "Error: Uncaught (in promise): Error: Template parse errors"

I've recently made an ng2 (using 2.0.1) app with multiple components and services. I'm in the middle of testing (Karma Jasmine) my HeaderComponent which contains my UserService (Which uses an extended Http class).
I've replicated simple tests from the Angular.io Docs to spy on a service and wait for after component initialization to check if the service function has been fired and its content. Every time I run the last test using fakeAsync (and async), which checks the content of the currentUser variable in header.component, I receive the following error...
Error: Uncaught (in promise): Error: Template parse errors:
'header-section' is not a known element:
1. If 'header-section' is an Angular component, then verify that it is part of this module.
2. If 'header-section' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '#NgModule.schemas' of this component to suppress this message. ("
[ERROR ->]<header-section></header-section>
<router-outlet></router-outlet>
<footer-section></footer-sectio"): AppComponent#1:2
'router-outlet' is not a known element:
1. If 'router-outlet' is an Angular component, then verify that it is part of this module.
2. If 'router-outlet' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '#NgModule.schemas' of this component to suppress this message. ("
<header-section></header-section>
[ERROR ->]<router-outlet></router-outlet>
<footer-section></footer-section>"): AppComponent#2:2
'footer-section' is not a known element:
1. If 'footer-section' is an Angular component, then verify that it is part of this module.
2. If 'footer-section' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '#NgModule.schemas' of this component to suppress this message. ("
<header-section></header-section>
<router-outlet></router-outlet>
[ERROR ->]<footer-section></footer-section>"): AppComponent#3:2
These selectors are from my AppComponent...
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'my-app',
moduleId: module.id,
template: `
<header-section></header-section>
<router-outlet></router-outlet>
<footer-section></footer-section>`
})
export class AppComponent {
constructor() {}
test(): string {
return 'this is a test';
}
}
My header.component.spec...
import { Http, Request, RequestOptionsArgs, Response, XHRBackend, RequestOptions, ConnectionBackend, Headers } from '#angular/http';
import { HttpIntercept } from '../../services/auth/auth.service';
import { BrowserModule } from '#angular/platform-browser';
import { HttpModule, JsonpModule } from '#angular/http';
import { FormsModule } from '#angular/forms';
import { RouterTestingModule } from "#angular/router/testing";
import { appRoutes } from '../../routes';
import { Cookie } from 'ng2-cookies/ng2-cookies';
import { AppComponent } from '../app/app.component';
import { HeaderComponent } from './header.component';
import { FooterComponent } from '../footer/footer.component';
import { HomeComponent } from '../home/home.component';
import { Four0FourComponent } from '../404/four0four.component';
import { UserProfileComponent } from '../user-profile/user-profile.component';
import { UserService } from '../../services/user/user.service';
import { ClockService } from '../../services/clock/clock.service';
import { Observable } from 'rxjs/Observable';
import { TestBed, async, fakeAsync, tick } from '#angular/core/testing';
import { By } from '#angular/platform-browser';
import { User } from '../../models/user/user.model';
class MockRouter { public navigate() { }; }
describe('HeaderComponent Test', () => {
let fixture;
let comp;
let userService;
let spy;
let user = new User({
_id: 123456,
userName: 'testName',
firstName: 'testFirst',
lastName: 'testLast',
email: 'test#email.com',
create: 'now',
role: 'user'
});
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
BrowserModule,
HttpModule,
FormsModule,
JsonpModule,
RouterTestingModule.withRoutes(appRoutes)
],
declarations: [
HomeComponent,
UserProfileComponent,
Four0FourComponent,
FooterComponent,
HeaderComponent,
AppComponent
],
providers: [
{
provide: Http,
useFactory: (
backend: XHRBackend,
defaultOptions: RequestOptions) =>
new HttpIntercept(backend, defaultOptions),
deps: [XHRBackend, RequestOptions]
},
Cookie
]
});
fixture = TestBed.createComponent(HeaderComponent);
comp = fixture.componentInstance;
userService = fixture.debugElement.injector.get(UserService);
spy = spyOn(userService, 'getMe')
.and.returnValue(Observable.of(user));
});
it('should instantiate component', () => {
expect(fixture.componentInstance instanceof HeaderComponent).toBe(true);
});
it('should not show currentUser before OnInit', () => {
expect(spy.calls.any()).toBe(false, 'getMe not yet called');
});
it('should still not show currentUser after component initialized', () => {
// Set cookie token, for the getMe to call
Cookie.set('token', 'test_token_alpha');
fixture.detectChanges();
expect(spy.calls.any()).toBe(true, 'getMe called');
});
//The problem test is bellow
it('should show currentUser after getMe promise', fakeAsync(() => {
fixture.detectChanges();
tick();
fixture.detectChanges();
expect(comp.currentUser).toEqual(user);
}));
});
Here's my header.component...
import { Component } from '#angular/core';
import { Cookie } from 'ng2-cookies/ng2-cookies';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/interval';
import { UserService } from '../../services/user/user.service';
import { ClockService } from '../../services/clock/clock.service';
import { User } from '../../models/user/user.model';
#Component({
selector: 'header-section',
providers: [
UserService,
ClockService
],
moduleId: module.id,
template: `
<style>
header{
background: rgb(55, 129, 215);
position: relative;
}
.user-sign{
position: absolute;
top:0;
right:0;
margin: 23px 5%;
}
.app-title{
font-family: cursive;
padding: 15px;
text-align: center;
font-size: 36px;
color: white;
}
.user-sign button:hover{
cursor: pointer;
}
.active{
color: orange;
}
</style>
<header>
<a routerLink='/' routerLinkActive='active'>Home</a>
<a routerLink='/profile' routerLinkActive='active'>Profile</a>
<a routerLink='/yoloswaq69420blazeitfgt' routerLinkActive='active'>404</a>
<div class='user-sign'>
<h3 *ngIf='currentUser'>Welcome, {{currentUser.userName}}</h3>
<button *ngIf='!currentUser' type='button' (click)='testRegisterUser()'>Sign up</button>
<button *ngIf='!currentUser' type='button' (click)='testUser()'>Sign in</button>
<button type='button' (click)='logout()'>Sign out</button>
</div>
<h1 class='app-title'>MEA2N Fullstack</h1>
</header>`
})
export class HeaderComponent {
errorMessage: string;
public currentUser: User;
clock = this.clockService.currentTime;
constructor(private userService: UserService, private clockService: ClockService) { }
ngOnInit() {
let token = Cookie.get('token');
if (token)
this.userService.getMe().subscribe(user => this.currentUser = user);
}
login(email: string, password: string) {
this.userService.login(email, password)
.subscribe(() => {
return this.userService.getMe()
.subscribe(user => {
this.currentUser = user;
})
});
}
logout() {
this.userService.logout();
this.currentUser = null;
}
registerUser(username: string, email: string, password: string) {
this.userService.signup(username, email, password)
.subscribe(() => {
return this.userService.getMe()
.subscribe(user => {
this.currentUser = user;
})
});
}
testUser() {
this.login('jc.thomas4214#gmail.com', 'flight1855');
}
testRegisterUser() {
this.registerUser('Jason', 'jc.thomas4214#gmail.com', 'flight1855');
}
}
I've suspected that this error is occurring because of how I'm initializing my TestBed.configureTestingModule().
I've tried...
Reordering both app.module and TestBed module declarations
adding schema: [CUSTOM_ELEMENTS_SCHEMA] to both modules
Since you are unit testing the Header component in this case, there is no need to include other modules and components
TestBed can look like this:
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
AppModule
],
providers: [
{provide: UserService, useClass: MockUserService},
{provide: ClockService, useClass: MockClockService}
]
});
fixture = TestBed.createComponent(HeaderComponent);
});
In this example the Services have been mocked but they can be spied too as you have correctly done for the UserService