如何测试承诺捕获块是否设置了this.error

时间:2018-12-20 09:34:34

标签: angular error-handling jasmine angular-promise

我有以下问题:

我想测试在承诺失败后是否将某些错误消息设置为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');
  });
});

1 个答案:

答案 0 :(得分:1)

您提供的链接为您提供了答案:

  

结合使用falseAsync和tick或flushMicroTasks   应该工作

因此,您应该像这样编写测试:

import { fakeAsync, flushMicrotasks, tick } from '@angular/core/testing';
...
it('signInWithGithub() Should sets POPUP_CLOSED error', fakeAsync(() => {
                                                        ^^^^^^^^^
  spyOn(componentService, 'loginwithGithubProvider')
    .and.returnValue(Promise.reject('auth/popup-closed-by-user'));

  component.signInWithGithub();
  flushMicrotasks(); // or tick();
  ^^^^^^^^^^^^^^^^^
  expect(component.loginError).toBe('The popup has been closed before authentication');
}));

Plunker Example