У меня есть следующая проблема:
Я хочу проверить, установлено ли определенное сообщение об ошибке this.loginError после сбоя обещания.Но похоже, что в любом случае тест не пройден, потому что обещание должно в конечном итоге разрешиться.
Я пробовал вещи, упомянутые в:
Но здесь успехов нет.У кого-нибудь есть идея, как мне это сделать?
Login.component.ts
import {Component, OnInit} from '@angular/core';
import {AuthService} from '../../services/auth/auth.service';
import {Router} from '@angular/router';
import {GithubService} from '../../services/github/github.service';
import {Errorcode} from './errorcode.enum';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.sass'],
})
export class LoginComponent implements OnInit {
public loginError: string | boolean = false;
constructor(public authService: AuthService, public router: Router, private data: GithubService) {
}
public signInWithGithub(): void {
this.authService.loginwithGithubProvider()
.then(this.loginError = null)
.catch(err => {
if (err === Errorcode.FIREBASE_POPUP_CLOSED) {
this.loginError = 'The popup has been closed before authentication';
}
if (err === Errorcode.FIREBASE_REQUEST_EXESS) {
this.loginError = 'To many requests to the server';
}
}
);
}
public logout(): void {
this.authService.logout();
}
ngOnInit() {
}
}
Login.component.spec.ts
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {LoginComponent} from './login.component';
import {AuthService} from '../../services/auth/auth.service';
import {MatCardModule} from '@angular/material';
import {AngularFireAuth} from '@angular/fire/auth';
import {AngularFireModule} from '@angular/fire';
import {environment} from '../../../environments/environment';
import {Router, RouterModule} from '@angular/router';
import {AngularFirestore} from '@angular/fire/firestore';
import {HttpClient, HttpHandler} from '@angular/common/http';
import {GithubService} from '../../services/github/github.service';
import {Observable} from 'rxjs';
import {promise} from 'selenium-webdriver';
import {any} from 'codelyzer/util/function';
class MockAuthService implements Partial<AuthService> {
isAuthenticated() {
return 'Mocked';
}
loginwithGithubProvider() {
return new Promise((resolve, reject) => resolve());
}
logout(): Promise<boolean | Observable<never> | never> {
return new Promise(function (resolve, reject) {
resolve();
});
}
}
describe('LoginComponent', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
let componentService: AuthService;
const routerSpy = jasmine.createSpyObj('Router', ['navigate']);
const ghServiceSpy = jasmine.createSpyObj('GithubService', ['methodName']);
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
MatCardModule,
AngularFireModule.initializeApp(environment.firebase),
RouterModule.forRoot([{path: '', component: LoginComponent}]),
],
declarations: [
LoginComponent
],
providers: [
AuthService,
AngularFirestore,
AngularFireAuth,
HttpClient,
HttpHandler
]
});
TestBed.overrideComponent(LoginComponent, {
set: {
providers: [
{provide: AuthService, useClass: MockAuthService},
{provide: Router, useValue: routerSpy},
{provide: GithubService, useValue: ghServiceSpy},
]
}
});
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
componentService = fixture.debugElement.injector.get(AuthService);
}));
it('should be created', () => {
expect(component).toBeTruthy();
});
it('Service injected via component should be an instance of MockAuthService', () => {
expect(componentService instanceof MockAuthService).toBeTruthy();
});
it('signInWithGithub() Should reset LoginError from false to null', async(() => {
expect(component.loginError).toEqual(false);
component.signInWithGithub();
expect(component.loginError).toBeNull();
}));
it('signInWithGithub() Should sets POPUP_CLOSED error ', async() => {
spyOn(componentService, 'loginwithGithubProvider')
.and.returnValue(Promise.reject('auth/popup-closed-by-user'));
component.signInWithGithub();
expect(component.loginError).toBe('The popup has been closed before authentication');
});
});