如何模拟服务Angular 7中的可观察值?

时间:2019-05-03 11:26:14

标签: angular typescript unit-testing jasmine

我一直在尝试为Angular组件编写单元测试。当前,在我的服务调用中,为获取我的组件的数据,我有一个可观察的对象,一旦调用完成,该对象为true。这在我的组件中可以观察到订阅,因此组件知道调用何时完成。我已经设法在组件中模拟了对数据的调用,但是我正在努力寻找一种方法来模拟单个可观察的值。

我能找到的所有关于SO的问题都是关于从组件中的服务模拟函数调用,但我找不到的是关于模拟单个可观察对象。

这是我在服务中的函数调用。如您所见,一旦finalize函数运行,可观察对象将被赋予一个新值:

  public getSmallInfoPanel(key: string): BehaviorSubject<InfoPanelResponse> {

    if (key) {
      this.infoPanel = new BehaviorSubject<InfoPanelResponse>(null);

      this.http.get(`${this.apiUrl}api/Panels/GetInfoPanel/${key}`).pipe(
          retry(3),
          finalize(() => {
            this.hasLoadedSubject.next(true);
          }))
        .subscribe((x: InfoPanelResponse) => this.infoPanel.next(x));
    }
    return this.infoPanel;
  }

这是我在服务中创建Observable的方式:

 private hasLoadedSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
 public hasLoadedObs: Observable<boolean> = this.hasLoadedSubject.asObservable();

然后在我的组件中,订阅从Observable创建的BehaviourSubject

public hasLoaded: boolean;

  ngOnInit() {

    this.infoPanelSmallService.hasLoadedObs.subscribe(z => this.hasLoaded = z);

  }

当我运行ng test时,组件测试失败,因为它不知道hasLoadedObs是什么,所以它无法订阅它。

让我知道是否可以提供更多信息。谢谢。

更新1

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

  let mockInfoPanelService;
  let mockInfoPanel: InfoPanel;
  let mockInfoPanelResponse: InfoPanelResponse;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        FontAwesomeModule,
        HttpClientTestingModule
      ],
      declarations: [InformationPanelSmallComponent, CmsInfoDirective],
      providers: [
        { provide: InfoPanelSmallService, useValue: mockInfoPanelService }
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {

    mockInfoPanel = {
      Title: 'some title',
      Heading: 'some heading',
      Description: 'some description',
      ButtonText: 'some button text',
      ButtonUrl: 'some button url',
      ImageUrl: 'some image url',
      Key: 'test-key',
      SearchUrl: '',
      VideoUrl: ''
    }

    mockInfoPanelResponse = {
      InfoPanel: mockInfoPanel
    }

    fixture = TestBed.createComponent(InformationPanelSmallComponent);
    component = fixture.componentInstance;

    mockInfoPanelService = jasmine.createSpyObj(['getSmallInfoPanel']);

    component = new InformationPanelSmallComponent(mockInfoPanelService);

    component.key = "test-key"

  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
  //TO DO
  it('should get info panel from info panel service', () => {
    mockInfoPanelService.getSmallInfoPanel.and.returnValue(of(mockInfoPanelResponse));
    component.ngOnInit();

    expect(mockInfoPanelService.getSmallInfoPanel).toHaveBeenCalled();
    expect(component.infoPanel).toEqual(mockInfoPanel);
  });
});


1 个答案:

答案 0 :(得分:0)

我发现这与我模拟服务和创建组件的顺序有关。我还使用了TestBed.overrideProvider,这与我上面使用的有所不同。这是最终的测试文件:


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

  let mockInfoPanelService;
  let mockInfoPanel: InfoPanel;
  let mockInfoPanelResponse: InfoPanelResponse;

  beforeEach(async(() => {
    mockInfoPanelService = jasmine.createSpyObj(['getSmallInfoPanel', 'hasLoadedObs']);

    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        FontAwesomeModule,
        HttpClientTestingModule
      ],
      declarations: [InformationPanelSmallComponent, CmsInfoDirective, UrlRedirectDirective],
      providers: [
        { provide: 'BASE_URL', useValue: '/' },
        { provide: 'API_URL', useValue: '/' }
      ]
    })

    TestBed.overrideProvider(InfoPanelSmallService, { useValue: mockInfoPanelService });

    TestBed.compileComponents();
  }));

  beforeEach(() => {

    mockInfoPanel = {
      Title: 'some title',
      Heading: 'some heading',
      Description: 'some description',
      ButtonText: 'some button text',
      ButtonUrl: 'some button url',
      ImageUrl: 'some image url',
      Key: 'test-key',
      SearchUrl: '',
      VideoUrl: ''
    }

    mockInfoPanelResponse = {
      InfoPanel: mockInfoPanel
    }

    fixture = TestBed.createComponent(InformationPanelSmallComponent);
    component = fixture.componentInstance;

    mockInfoPanelService.getSmallInfoPanel.and.returnValue(of(mockInfoPanelResponse));
    mockInfoPanelService.hasLoadedObs = of(true);

    component.key = "test-key"

    fixture.detectChanges();

  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  describe('ngOnInit', () => {
    it('should get info panel from info panel service', () => {
      expect(component.hasLoaded).toEqual(true);
      expect(mockInfoPanelService.getSmallInfoPanel).toHaveBeenCalled();
      expect(component.infoPanel).toEqual(mockInfoPanel);
    });

    it('should get loaded is true from service', () => {
      expect(component.hasLoaded).toEqual(true);
    });
  });
});

然后我再也没有错误,并且测试实际上可以正常运行。感谢@RuiMarques和其他人的所有输入。