gpt4 book ai didi

angular - 如何测试Promise catch block 是否设置了this.error

转载 作者:行者123 更新时间:2023-12-03 07:52:56 26 4
gpt4 key购买 nike

我有以下问题:

我要测试 promise 失败后是否将某些错误消息设置为this.loginError。但是似乎测试还是失败了,因为 promise 必须最终解决。

我已经尝试了以下内容中提到的内容:

  • How to unit test Promise catch using Jasmine
  • Test for rejected promise with Jasmine

  • 但是这里没有成功。
    有人知道我该怎么做吗?

    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');
    });
    });

    最佳答案

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

    using fakeAsync in conjunction with either tick or flushMicroTasks should work



    因此,您应该像这样编写测试:
    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

    关于angular - 如何测试Promise catch block 是否设置了this.error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53865858/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com