如何在“.subscribe()”Angular/Jasmine 中测试代码

问题描述

我的 StatisticComponent

中有此代码
this.subscription = this.locationService.getStatisticOne(this.formService.getFormValue())
  .subscribe(data => {
    this.array = data;
    this.wrongValueOne = this.array.shift();
    for (let array of this.array) {
      this.addData(this.myChartOne,array.date,array.leistung);
    }
  });

现在我想编写一个测试来查看是否正在调用或执行此 .subscribe() 函数中的任何内容。此代码片段在 generateStatisticOne() 函数内执行,该函数getData() 函数调用,该函数ngOnInit() 中或按下按钮时调用。问题是我刚开始编写测试,甚至不知道我在这里找到的东西是否有意义,但我现在有这个测试代码

describe('StatisticComponent',() => {
  let component: StatisticComponent;
  let fixture: ComponentFixture<StatisticComponent>;

  const locationServiceSpy = jasmine.createSpyObj('LocationService',{
    getStatisticOne: of([{ id: 1 },{ id: 2 },{ id: 3 }])
  });


  beforeEach(async () => {
    await Testbed.configureTestingModule({
      declarations: [StatisticComponent],imports: [
        HttpClientTestingModule
      ],providers: [{ provide: LocationService,useValue: locationServiceSpy },LocationService,HttpClientTestingModule
      ],})
      .compileComponents();
  });

  beforeEach(() => {
    fixture = Testbed.createComponent(StatisticComponent);
    component = fixture.componentInstance;
    locationService = Testbed.get(LocationService);
    fixture.detectChanges();
  });

  it('should call array.shift ',fakeAsync(() => {
    const service = Testbed.get(LocationService); // get your service
    spyOn(service,'getStatisticOne').and.callThrough(); // create spy
    spyOn(Array.prototype,'shift');
    fixture.detectChanges();
    tick();
    expect(Array.prototype.shift).toHaveBeenCalled();
  }));

我在运行代码时得到的错误是“预期的间谍转移已被调用

解决方法

您需要做的第一件事是将您的测试一分为二。第一组测试将实例化服务并使用 HttpClientTestingModule 模拟 HttpClient,第二组测试将实例化组件并模拟服务。这样你就可以清楚地区分正在测试的内容和边界所在的位置。 为了回答您关于如何测试订阅方法的问题,一旦您模拟了服务,您就可以使用 rxjs 可观察库中的 of() 响应方法调用,并且在那里您可以模拟数据以查看你想要。