简体   繁体   English

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

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

I have the following service code我有以下服务代码

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

Note: This service uses a file that has specific static conntant variables.注意:此服务使用具有特定静态常量变量的文件。

I am trying to mock the AppConstants.apiBaseUrl variable in the .spec file as below我正在尝试模拟 .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);
    });

It always getting undefined in the apiBaseUrl property.它总是在 apiBaseUrl 属性中未定义。 Any quick help will be much appreciated.任何快速帮助将不胜感激。

I have tried the spyOn method to create mock objects but it didn't help.我尝试过 spyOn 方法来创建模拟对象,但没有帮助。

leave providers in a simple way.以简单的方式离开提供者。 you are providing a spy() now instead of the class.您现在提供的是 spy() 而不是课程。

providers: [
                ApiService,
                AppConstants
            ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM