I am just starting to configure my testing environment for my Angular 6 app. What's the best way for me to simulate a user logging in, so that my test passes? I have an AuthService, but only want to inject a mock of the service.
The line of code in the .ts file causing the issue is this.authService.userSession.authToken
and the error reads Cannot read property 'authToken' of undefined
Here's my edit-site.component.spec.ts file so far, where I attempt to create a mock auth service
import { NavigationComponent } from '../navigation/navigation.component';
import { EditSiteComponent } from './edit-site.component';
import { FormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';
import { MatDialog, MAT_DIALOG_SCROLL_STRATEGY } from '@angular/material';
import { Overlay } from '@angular/cdk/overlay';
import { HttpClient, HttpHandler } from '@angular/common/http';
import { InjectionToken } from '@angular/core';
import { AuthService } from '../../services/auth.service'
import { UserSession } from 'src/app/models/user-session';
describe('EditSiteComponent', () => {
let component: EditSiteComponent;
let fixture: ComponentFixture<EditSiteComponent>;
class MockAuthService {
isLoggedIn = true;
user = { name: 'Test User'};
authToken = '123456789'
};
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ FormsModule, RouterTestingModule ],
declarations: [ EditSiteComponent, NavigationComponent ],
providers: [{provide: AuthService, useValue: MockAuthService}, MatDialog, Overlay, HttpClient, HttpHandler, {provide: MAT_DIALOG_SCROLL_STRATEGY, useValue:{}}]
})
.compileComponents();
}));
beforeEach(() => {
let userSession = MockAuthService
fixture = TestBed.createComponent(EditSiteComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
In my auth.service.ts file is
public get userSession(): UserSession {
return this._userSession;
}
which references the model user-session.ts
import { ApplicationModel } from "./application-model";
import { SiteModel } from "./site-model";
export class UserSession {
public _authToken: string;
private _userContext: UserContext;
public _currentApplication: ApplicationModel;
constructor(authToken: string, userContext: UserContext) {
this._authToken = authToken;
this._userContext = userContext;
}
get authToken(): string {
return this._authToken;
}
get userContext(): UserContext {
return this._userContext;
}
get currentApplication(): ApplicationModel {
return this._currentApplication;
}
set currentApplication(currentApplication: ApplicationModel) {
this._currentApplication = currentApplication;
}
}
Thank you so much!
Aucun commentaire:
Enregistrer un commentaire