繁体   English   中英

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

[英]Angular w/ Jasmine and Karma testing a mock service

我想使用 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', []))
      );
  }

}

和 me.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();
  });

});

您可以注入它并创建间谍来模拟您尝试模拟/测试的任何内容:

const aboutService = TestBed.inject(AboutService);

const spy = spyOn(aboutService, 'getSkills').and.returnValue(of({...});
...
expect(spy).toHaveBeenCalled();

暂无
暂无

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

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