簡體   English   中英

NativeScript - 單元測試 HttpInterceptor NSLocationStrategy 錯誤

[英]NativeScript - unit testing an HttpInterceptor NSLocationStrategy error

我正在使用 NativeScript 6.4.1 和 Angular 8 編寫應用程序。

我想為我的 HttpInterceptor 編寫單元測試。 如果用戶從后端收到某些錯誤,我的攔截器會添加一個令牌來選擇 http 調用並將用戶路由到身份驗證頁面。

代碼運行良好,但我的單元測試沒有。

當我運行單元測試時,出現此錯誤:

NullInjectorError: StaticInjectorError(DynamicTestModule)[RouterExtensions -> NSLocationStrategy]:
  StaticInjectorError(Platform: core)[RouterExtensions -> NSLocationStrategy]:
    NullInjectorError: No provider for NSLocationStrategy!
error properties: Object({ originalStack: 'Error: NullInjectorError: No provider for NSLocationStrategy!
    at new ZoneAwareError (file:///data/data/org.nativescript.SelfServiceApp/files/app/vendor.js:157861:33)

我不知道為什么我收到錯誤。

這是我的單元測試:

import { nsTestBedBeforeEach } from 'nativescript-angular/testing';
import { TestBed } from '@angular/core/testing';
import { HttpInterceptorService } from '~/app/core/interceptors/http-interceptor-service';
import { HttpLoaderService } from '~/app/core/shared/http-loader.service';
import { AuthenticationService } from '~/app/authentication/shared/services/authentication.service';
import { SsoAuthenticationService } from '~/app/authentication/pages/single-sign-on/sso-authentication.service';
import { EndpointHelperService } from '~/app/core/shared/endpoint-helper.service';
import { RouterExtensions } from 'nativescript-angular/router';

import { HttpClientTestingModule } from '@angular/common/http/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { NativeScriptRouterModule } from 'nativescript-angular/router';
import { Routes, RouterModule } from '@angular/router';
import { CommonModule, Location } from '@angular/common';

describe('HttpInterceptorService Test', () => {

    let service: HttpInterceptorService;

    beforeEach(nsTestBedBeforeEach([], [
        HttpInterceptorService,
        HttpLoaderService,
        AuthenticationService,
        SsoAuthenticationService,
        EndpointHelperService,
        RouterExtensions
    ], [
        HttpClientTestingModule, 
        RouterTestingModule, 
        NativeScriptRouterModule, 
        CommonModule
    ]));

    it('should be defined', () => {
        service = TestBed.get(HttpInterceptorService);
        expect(service).toBeTruthy();
    });
});

這是我的攔截器:

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, throwError, from } from 'rxjs';
import { tap, catchError } from 'rxjs/operators';
import { HttpLoaderService } from '../shared/http-loader.service';
import { boundMethod } from 'autobind-decorator';
import { AuthenticationService } from '../../authentication/shared/services/authentication.service';
import { SsoAuthenticationService } from '../../authentication/pages/single-sign-on/sso-authentication.service';
import { EndpointHelperService } from '../shared/endpoint-helper.service';
import { switchMap } from 'rxjs/operators';
import { RouterExtensions } from 'nativescript-angular/router';

@Injectable()
export class HttpInterceptorService implements HttpInterceptor {

    constructor(
        private httpLoaderService: HttpLoaderService,
        private authentication: AuthenticationService,
        private ssoAuthentication: SsoAuthenticationService,
        private endpointHelper: EndpointHelperService,
        private router: RouterExtensions
    ) {}

    public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        this.httpLoaderService.onRequestStart();

        // do not add to token endpoints
        if (this.endpointHelper.isTokenEndpoint(request.url)) {
            return this.returnRequest(request, next);
        }

        //do not add to registration server
        if (this.endpointHelper.isRegisterEndpoint(request.url)) {
            return this.returnRequest(request, next);
        }

        return this.appendSSOTokenToHeader(request, next);
    }

    @boundMethod
    private appendSSOTokenToHeader(request: HttpRequest<any>, next: HttpHandler) {

        return from(this.ssoAuthentication.getHttpHeader())
            .pipe(
                switchMap((newHeader) => {

                    request = request.clone({ 
                        body: { ...request.body, clientcode: this.authentication.clientcode },
                        setHeaders: { Authorization: newHeader },
                        url: this.authentication.mobileApiUrl + request.url
                    });

                    return this.returnRequest(request, next);
                })
            );
    }

    @boundMethod
    private returnRequest(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next
            .handle(request)
            .pipe(tap(this.handleSuccess), catchError(this.handleError));
    }

    @boundMethod
    private handleSuccess(event: HttpEvent<any>): void {
        if (event instanceof HttpResponse) {
            this.httpLoaderService.onRequestEnd();
        }
    }

    @boundMethod
    private handleError(error: HttpErrorResponse) {

        this.httpLoaderService.onRequestEnd();

        if (this.endpointHelper.shouldRedirectToSSOPage(error)) {
            this.router.navigate(['register-via-sso']);
        }

        return throwError(error);
    }

}

你必須加載NativeScriptRouterModuleNativeScriptRouterModule.forRoot([])它與可用路由您的應用程序模塊類似於加載路由器。 由於它是單元測試,因此您不會在這里傳遞路由。

暫無
暫無

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

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