我想为组件编写单元测试,这取决于服务,哪个方法取参数,更重要的是,我使用onPush变化检测,所以在该组件的视图中我显示了来自服务的主题的Observable .

我已经遵循了一些教程,当然,这是由Angular团队准备的,但是当测试方法需要参数时,我无处可以找到这种情况,更常见的是由他们准备的服务模拟返回现成的数组,不能观察到数组我订阅了 .

目前,我已经编写了这样的测试,但是对我来说什么是混乱,我无法声明我的方法需要参数

describe('PeopleProfileComponent', () => {
  let comp: PeopleProfileComponent;
  let fixture: ComponentFixture<PeopleProfileComponent>;
  let matDialogRef: MatDialogRef<PeopleProfileComponent>;
  let peopleId: number = 1;
  let getPeopleSpy: jasmine.Spy;
  let de: DebugElement;  // the DebugElement with the welcome message
  let el: HTMLElement; // the DOM element with the welcome message
  let testPeople = new People();
  beforeEach(() => {
   // Create a fake PeopleServiceServiceobject with a `getPeopleById()` spy
   const peopleService = jasmine.createSpyObj('PeopleServiceService', 
   ['getPeopleById']);
   // Make the spy return a synchronous Observable with the test dat
   getPeopleSpy = 
   peopleService.getPeopleById.and.returnValue(of(testPeople));
   TestBed.configureTestingModule({
      declarations: [PeopleProfileComponent],
      providers: [{ provide: MatDialogRef }, { provide: MAT_DIALOG_DATA, 
      useValue: 1 }, { provide: PeopleServiceService, useValue: { 
      peopleService } 
   },]
   })
     .compileComponents().then(() => {

      fixture = TestBed.createComponent(PeopleProfileComponent);
      comp = fixture.componentInstance;
      matDialogRef = TestBed.get(MatDialogRef);
      el = fixture.nativeElement.querySelector('.container');
    });
  });

在那一行,我得到了一个错误

fixture = TestBed.createComponent(PeopleProfileComponent);

未处理的Promise拒绝:this.peopleService.getPeopleById不是函数;区域:ProxyZone;任务:Promise.then;值:TypeError:this.peopleService.getPeopleById不是函数

我的组件看起来像

import { Component, OnInit, Inject, ChangeDetectionStrategy } from 
'@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { People } from '../people';
import { PeopleServiceService } from '../service/people-service.service';

@Component({
selector: 'app-people-profile',
templateUrl: './people-profile.component.html',
styleUrls: ['./people-profile.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class PeopleProfileComponent implements OnInit {
people: People;
constructor(
  public dialogRef: MatDialogRef<PeopleProfileComponent>,
  @Inject(MAT_DIALOG_DATA) public peopleId: number,
  private peopleService: PeopleServiceService) {
  if (peopleId) {  
    this.peopleService.getPeopleById(peopleId).subscribe(
      (people: People) => {
        this.people = people;
        this.peopleService.changePeople(people);
      },
      error => { },
      () => {  });
  }
 }

ngOnInit() {
}

}

这也是我的组件所依赖的服务

export class PeopleServiceService {
  private subject = new BehaviorSubject<People>(new People());
  people$: Observable<People> = this.subject.asObservable();
  private arraySubject = new BehaviorSubject<People []>(new Array<People>());
  peopleArray$: Observable<People []> = this.arraySubject.asObservable();
  private searchingSubject = new BehaviorSubject<boolean>(false);
  isSearching$: Observable<boolean> = this.searchingSubject.asObservable();

  constructor(private httpClient: HttpClient, private snackBar: MatSnackBar) { }

  getPeople(): Observable<People[]> {
    return this.httpClient.get(`/people`).pipe(
      map((response: any): People[] => response),
      catchError(this.handleError<People[]>('getPeople')),
      finalize(() => {
        this.changeIsSearching(false);
      })
    )
  }

  getPeopleById(peopleId: number): Observable<People> {
    return this.httpClient.get(`/people/${peopleId}`).pipe(
      map((response: any): People => response),
      catchError(this.handleError<People>(`getPeople id=${peopleId}`)),
      finalize(() => {
        this.changeIsSearching(false);
      })
    )
  }

我知道我们应该模拟服务,当我在单元测试中将PeopleServiceService(这是真正的服务)替换为PeopleServiceMock时,我得到了错误的错误

未处理的Promise拒绝:StaticInjectorError(DynamicTestModule)[HttpClient]:StaticInjectorError(Platform:core)[HttpClient]:NullInjectorError:没有HttpClient的提供者! ;区域:ProxyZone;任务:Promise.then;值:错误:

它是PeopleServiceMock

@Injectable()
export class PeopleServiceMock {
    tempPeople: People[] = [
        {
            id: 1,
            first_name: 'John',
            last_name: 'John'
        },
        {
            id: 2,
            first_name: 'John',
            last_name: 'John'
        }
    ];
    constructor() { }

    getPeople(): Array<{}> {
        return this.tempPeople;
    }

    getPeopleById(id: number) : Observable<People>  {
        return of(this.tempPeople.find(people => people.id == id))
    }
}

你能说出我做错了什么或给出了一些我可以遵循的好教程吗?