【问题标题】:How do I test code inside ".subscribe()" Angular/Jasmine如何在“.subscribe()”Angular/Jasmine 中测试代码
【发布时间】:2021-01-15 11:32:06
【问题描述】:

我的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() 函数中是否有任何东西被调用或执行。此代码 sn-p 在 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();
  }));

我在运行代码时遇到的错误是“expected spy shift to have been called”

【问题讨论】:

  • 首先,您可以尝试在shift (spyOn(Array.prototype, 'shift').and.callThrough(); 上调整您的间谍,但更好的办法是检查您的subscribe 回调的预期结果 . 你应该检查arraywrongValueOne 是否等于你的期望。
  • 感谢您的快速回答,但预期的结果永远不会发生,因为在订阅方法完成后更改似乎会丢失。我使用 subscribe 提取数据并将其添加到来自 chart.js 的图表中。如果您可能知道如何检查该结果,我会很高兴,但 wrongValueOnearray 不能像那样进行测试(或者我错过了一些重要的东西)

标签: angular testing jasmine subscribe


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-21
    • 2014-09-16
    • 2019-07-14
    • 2021-02-12
    • 2014-09-30
    • 2016-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多