首页 > 解决方案 > 如何在“.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();
  }));

运行代码时出现的错误是“预期的间谍转移已被调用”

标签: angulartestingjasminesubscribe

解决方案


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


推荐阅读