角度8:如何使用Jasmine监视常量/静态属性(服务单元测试)

问题描述 投票:0回答:1

我有以下服务代码

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方法创建模拟对象,但没有帮助。

angular unit-testing mocking
1个回答
0
投票

以一种简单的方式离开提供商。您现在提供的是spy()而不是类。

providers: [
                ApiService,
                AppConstants
            ]
© www.soinside.com 2019 - 2024. All rights reserved.