Angular w / Jasmine和Karma测试了模拟服务

问题描述

我想使用Jasmine / Karma来测试模拟服务,而无需了解真正的服务。问题是它希望我添加真实服务中的所有依赖项,例如HttpErrorHandler和MessageService。

这是下面的真实服务代码:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { httpOptions } from '../http-options';
import { HttpErrorHandler,HandleError } from '../http-error-handler.service';
//
@Injectable({ providedIn: 'root' })
export class AboutService {
  private handleError: HandleError;

  constructor(
    private http: HttpClient,httpErrorHandler: HttpErrorHandler
    ) {
    this.handleError = httpErrorHandler.createHandleError('AboutService');
  }

  // Skills
  ////////
  getSkills() {
    const url = 'path';

    return this.http.get<any>(url,httpOptions)
      .pipe(
        catchError(this.handleError('getSkills',[]))
      );
  }

}

和我的.spec文件

import { async,ComponentFixture,TestBed } from '@angular/core/testing';

import { AboutComponent } from './about.component';
// 
import { HttpClientTestingModule,HttpTestingController } from '@angular/common/http/testing';// Other imports
import { AboutService } from './about.service';
// import { HttpErrorHandler } from '../http-error-handler.service';
// import { MessageService } from '../message.service';
// import { MaterialModule } from "../material/material.module";

class MocksService extends AboutService{
  // getSkills() {
  //     return [someRandomArray];
  // }
}

describe('AboutComponent',() => {
  let component: AboutComponent;
  let fixture: ComponentFixture<AboutComponent>;
  // 
  let httpTestingController: HttpTestingController;
  let service: AboutService;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ AboutComponent ],imports: [ HttpClientTestingModule,MaterialModule ],providers: [ 
        { AboutService,useClass: MocksService },// HttpErrorHandler,// MessageService
      ]
    })
    .compileComponents();

    // 
    httpTestingController = TestBed.get(HttpTestingController);
    service = TestBed.get(AboutService);

  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AboutComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create',() => {
    expect(component).toBeTruthy();
  });

  it('should be created',() => {
    const service: AboutService = TestBed.get(AboutService);
    expect(service).toBeTruthy();
  });

});

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)