簡體   English   中英

Angular 8:如何使用 Jasmine 監視常量/靜態屬性(服務單元測試)

[英]Angular 8: How to spy a constant/static property with Jasmine (Service Unit Testing)

我有以下服務代碼

import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AppConstants } from 'src/app/constants';
import * as _ from 'underscore';

import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
    providedIn: 'root'
})

export class ApiService {
    constructor(private httpClient: HttpClient) { }

    get(url: string, options?: any): Observable<any> {
        // console.log('2. AppConstants', AppConstants.apiBaseUrl);
        const requestURL = `${AppConstants.apiBaseUrl}${url}`;
        console.log('url---', requestURL);
        return this.httpClient.get(requestURL, options).pipe(
            catchError(this.handleError)
        );
    }

    post(url: string, body: any, options?: any): Observable<any> {
        return this.httpClient.post(`${AppConstants.apiBaseUrl}${url}`, body, options).pipe(
            catchError(this.handleError)
        );
    }

    put(url: string, body: any, options?: any): Observable<any> {
        return this.httpClient.put(`${AppConstants.apiBaseUrl}${url}`, body, options).pipe(
            catchError(this.handleError)
        );
    }

    delete(url: string, options?: any): Observable<any> {
        return this.httpClient.delete(`${AppConstants.apiBaseUrl}${url}`, options).pipe(
            catchError(this.handleError)
        );
    }

    private handleError(error: HttpErrorResponse) {
        if (_.isUndefined(error) && _.isNull(error)) {
            throwError(error);
        }

        if (error.error instanceof ErrorEvent) {
            // A client-side or network error occurred. Handle it accordingly.
            console.error('An error occurred:', error.error.message);
        } else {
            // The backend returned an unsuccessful response code.
            // The response body may contain clues as to what went wrong,
            console.error(
                `Api returned an error with code ${error.status}, ` +
                `error body was: ${error.error}`);
        }
        return throwError(error.error);
    }
}

注意:此服務使用具有特定靜態常量變量的文件。

我正在嘗試模擬 .spec 文件中的 AppConstants.apiBaseUrl 變量,如下所示

import { AppConstants } from 'src/app/constants';
import { HttpTestingController, HttpClientTestingModule } from '@angular/common/http/testing';
import { async, inject, TestBed } from '@angular/core/testing';

import { ApiService } from './api.service';

class MockAppConstants {
    public static apiBaseUrl = 'test-base-api-url';
}

describe('ApiService', () => {
    // const spy = spyOnProperty(AppConstants, 'apiBaseUrl', 'get').and.returnValue('base-api-url');
    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [
                HttpClientTestingModule
            ],
            providers: [
                ApiService
                ,
                {
                    provide: AppConstants,
                    useValue: spy
                }
            ]
        });
    }
    );

    it('should get profile data of user', () => {
        const profileInfo = { login: 'blacksonic', id: 602571, name: 'Gábor Soós' };
        const githubService = TestBed.get(ApiService);
        const appConstants = TestBed.get(AppConstants);
        const http = TestBed.get(HttpTestingController);
        let profileResponse;

        githubService.get('blacksonic').subscribe((response) => {
            profileResponse = response;
        });

        http.expectOne('undefinedblacksonic').flush(profileInfo);
        expect(profileResponse).toEqual(profileInfo);
    });

它總是在 apiBaseUrl 屬性中未定義。 任何快速幫助將不勝感激。

我嘗試過 spyOn 方法來創建模擬對象,但沒有幫助。

以簡單的方式離開提供者。 您現在提供的是 spy() 而不是課程。

providers: [
                ApiService,
                AppConstants
            ]

暫無
暫無

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

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