具有http和其他依赖项的Angular Service测试

时间:2020-03-10 05:30:53

标签: angular karma-jasmine angular-httpclient angular-testing

我为httpclient编写了一个包装器,该包装器从可观察的位置设置配置,并且在出现错误的情况下也使用toastr。除去其他两个构造函数注入后,它不会失败。

如果我模拟RestService,则不能使用HttpTestingController,它提供了其他有用的方法来进行httpclient测试

rest.service.ts

@Injectable()
export class RestService {
    public baseUrl = null;

    constructor(
        private http: HttpClient,
        private appConfigService: AppConfigService,
        private toast: ToastNotificationService,
    ) {
        this.getConfig();
    }

    get<T>(url, showError = true): Observable<any> {
        return this.http.get<T>(this.baseUrl + url).pipe(
            catchError((error: HttpErrorResponse) => {
                return this.showError(error, showError);
            }),
        );
    }

    private getConfig() {
        this.appConfigService.appConfig$.subscribe(env => {
            this.baseUrl = env.backendUrl + API_PREFIX;
        });
    }

    private showError(error: HttpErrorResponse, showError) {
        let message = Helpers.getErrorMessageFromObject(error);
        if (showError && message) this.toast.showError(message);

        return throwError(error);
    }   
}

rest.service.spec.ts

import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { AppConfigService } from './app-config.service';
import { RestService } from './rest.service';
import { ToastNotificationService } from './toast-notification.service';

describe('RestService', () => {
    let service: RestService;
    let httpMock: HttpTestingController;
    const testData = { name: 'Test Data' };

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [HttpClientTestingModule],
            providers: [
                RestService,
                {
                    provide: AppConfigService,
                    useValue: jasmine.createSpyObj({
                        appConfig$: of(),
                    }),
                },
                {
                    provide: ToastNotificationService,
                    useValue: jasmine.createSpyObj({
                        showError: function () { },
                    }),
                },
            ],
        });

        service = TestBed.get(RestService);
        httpMock = TestBed.get(HttpTestingController);
    });

    afterEach(() => {
        httpMock.verify();
    });

    it('should be created', () => {
        expect(service).toBeTruthy();
    });

    it('should get the data successful', () => {
        service.baseUrl = '';
        const endpoint = '/api/v1/features/1';

        service.get(endpoint).subscribe((data: any) => {
            expect(data).toEqual(testData);
            expect(service.get).toHaveBeenCalled();
            expect(service.get).toHaveBeenCalledWith(endpoint);
        });

        const req = httpMock.expectOne(endpoint);
        expect(req.request.method).toBe('GET');
        req.flush(testData);
    });
});

0 个答案:

没有答案