簡體   English   中英

Angular/Jasmine:無法讀取未定義的屬性“管道”

[英]Angular/Jasmine: Cannot read property 'pipe' of undefined

我嘗試了很多解決 Angular 9、Jasmine 和 RxJS 的問題,但我沒有成功。 我的單元測試由 Jasmine 運行,但我沒有執行某些行代碼。

我一直在尋找幾篇文章的幫助,但這些文章都沒有提供適合我的問題的解決方案,我對此感到非常沮喪。

我需要幫助,請:)

班級考試

describe('AuthRefreshAppInterceptor', () => {
    let accessToken: string;
    let endpoint: string;

    let authAppServiceMock: AuthAppService;
    let baseHTTPService: BaseHTTPService;
    let environmentServiceMock: EnvironmentService;
    let httpTestingController: HttpTestingController;
    let sessionStorageServiceMock: SessionStorageService;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [HttpClientTestingModule],
            providers: [
                CriptografiaService,
                BaseHTTPService,
                {
                    provide: AuthAppService,
                    useValue: jasmine.createSpyObj('AuthAppService', ['getNewAuth', 'saveAuth', 'createBodyAuth', 'createBodyAuth'])
                },
                {
                    provide: EnvironmentService,
                    useValue: EnvironmentMock
                },
                {
                    provide: HTTP_INTERCEPTORS,
                    useClass: AutorizacaoErroAppInterceptor,
                    multi: true,
                },
                {
                    provide: SessionStorageService,
                    useValue: jasmine.createSpyObj('SessionStorageService', ['saveItem', 'getItem', 'removeItem'])
                }
            ],
        });

        authAppServiceMock = TestBed.inject(AuthAppService);
        baseHTTPService = TestBed.inject(BaseHTTPService);
        environmentServiceMock = TestBed.inject(EnvironmentService);
        httpTestingController = TestBed.inject(HttpTestingController);
        sessionStorageServiceMock = TestBed.inject(SessionStorageService);

        accessToken = faker.finance.bitcoinAddress();
        endpoint = faker.internet.domainName();

        sessionStorageServiceMock.getItem = jasmine.createSpy()
            .and.returnValue({ access_token: accessToken });
    });

    afterEach(() => {
        httpTestingController.verify();

        authAppServiceMock.obterAutorizacaoApp = jasmine.createSpy()
            .and.returnValue(Observable.of({
                access_token: 'eyJhbGciOiJSUzI1NiIsImtpZCI6Ik5oMXY4YlZsODg2M3g3UnhWTlJhamciLCJ0eXAiOiJhdCtqd3QifQ.eyJuYmYiOjE1OTE3OTU5MjAsImV4cCI6MTU5MTc5OTUyRJhdnjh78sjiHDhdiajsd9sb2NhbGhvc3Q6NTUwMDEiLCJhdWQiOiJJZGVudGl0eVNlcnZlckFwaSIsImNsaWVudF9pZCI6IkFkbWluIiwic2NvcGUiOlsiSWRlbnR86d5F4dasdf.Gvxq02a2HaF4rpeB3KnBxRAHHa6WpU850V5377wpRBAA6rmw6PRzVRMnpd2mtr5CVY72NWCspsdU8a8XhwFTgoCDmjSlXKSZKmUGsEaCbXuzSQg7BwD7A9zul0U0VkbF1KTvLIdnmb1noyeOP04dDH',
                expires_in: 3600,
                token_type: 'Bearer',
                scope: 'IdentityServerApi'
              }));
    });

    it('Should executed a request GET and return a HtttpErrorResponse with error 401 Unauthorized', () => {
        spyOn(baseHTTPService, 'httpGet').and.callThrough();

        baseHTTPService.httpGet(endpoint).subscribe({
            error: (httpErrorResponse: HttpErrorResponse) => {
                console.log(httpErrorResponse)
                expect(httpErrorResponse.status).toEqual(401);
                expect(httpErrorResponse.statusText).toEqual('Unauthorized');
                expect(httpErrorResponse.message).toContain('Http failure response for');
            }
        });

        const httpRequest = httpTestingController.expectOne(
            `${environmentServiceMock.apiGatewayURL}/${endpoint}`
        );
        httpRequest.flush(null, { status: 401, statusText: 'Unauthorized' });

        expect(baseHTTPService.httpGet).toHaveBeenCalledTimes(1);
        expect(httpRequest.request.url).toBe(`${environmentServiceMock.apiGatewayURL}/${endpoint}`);
        expect(httpRequest.request.method).toBe('GET');
        expect(httpRequest.request.body).toBeNull();
    });
    ...
});

攔截器:測試類

export class AuthRefreshAppInterceptor {
    ...
    private getNewAuth(request: HttpRequest<any>, next: HttpHandler) {
        return this.authAppService
            .getAuthApp()
            .pipe(
                // THIS BLOCK IS NOT TESTED
                switchMap((auth: AuthAppModel) => {
                    this.authAppService.saveAuth(auth);
                    return next.handle(this.addHeaders(request));
                }),
                // THIS BLOCK IS NOT TESTED
                catchError(() => next.handle(request))
            );
    }
    ...
}

服務

export class AuthAppService {
    ...
    public salvarAutorizacao(auth: AuthAppModel) {
        this.sessionStorageService.removeItem(this.authKey);
        this.sessionStorageService.saveItem(this.authKey, auth);
    }
    
    public getAuthApp(): Observable<AuthAppModel> {
        return this.httpClient.post<AuthAppModel>(
            `${this.environmentService.apiGateway}/identity/token`,
            this.createBodyAuth(),
            { headers: this.createHeaders() }
        );
    }
    ...
}

謝謝

您必須在getAuthApp作為方法jasmine.createSpyObj

 {
   provide: AuthAppService,
   useValue: jasmine.createSpyObj('AuthAppService', ['getAuthApp' 'getNewAuth', 'saveAuth', 'createBodyAuth', 'createBodyAuth']) // add 'getAuthApp' here
 },

對於success path (switchMap)

import { of } from 'rxjs';
....
// at the beginning of you test mock these
authAppServiceMock.getAuthApp.and.returnValue(of({})); // put your mock value here
authAppServiceMock.saveAuth.and.returnValue(of({})); // put your mock value here
... proceed with your test

對於fail path (catchError)

import { throwError } from 'rxjs';
....
// at the beginning of you test mock this
authAppServiceMock.getAuthApp.and.returnValue(throwError({})); // mock your throw error here so it goes into catchError
.... proceed with your test

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM