测试广播服务

问题描述 投票:0回答:1

嗨,我正在尝试为具有可观察性的组件编写角度代码,但无法测试广播服务。我收到一条错误消息,说未调用该服务。我应该如何使用该服务?任何帮助,将不胜感激。谢谢。

这是我的组件,具有可观察的:

  ngOnInit(): void {

    this.subscription.add(
      this.broadcastService.subscribe('msal:acquireTokenSuccess', (payload) => {
        // do something here
        this.roleService.checkServerEventReviewers().subscribe(res => {
          this.userService.userDetails.role = res ? 'Data Steward' : 'Mosaic Consumer';
          if (this.isLoggedIn !== true) {
            const redirectUri = sessionStorage.getItem('redirectUri');
            if (redirectUri !== undefined || redirectUri !== null) {
              this.router.navigateByUrl(redirectUri);
            }
          }
          this.isLoggedIn = true;
};

这是我正在尝试的规格文件:

  describe(':', () => {
    function setup() {
      const fixture = TestBed.createComponent(AppComponent);
      const app = fixture.debugElement.componentInstance;
      const compiled = fixture.debugElement.nativeElement;
      return {fixture, app, compiled};
    }

    it('Init with QA environment', () => {
      const {app} = setup();
      spyOn(app.authService, 'getUser').and.returnValue(mockData.userDetails);
      spyOn(app.authService, 'acquireTokenSilent').and.returnValue('msal:acquireTokenSuccess');
      app.ngOnInit();
      spyOn(app.broadcastService,'subscribe');
      expect(app.broadcastService.subscribe).toHaveBeenCalled();
    );
angular unit-testing testing angular7 msal
1个回答
0
投票

问题是您没有在TestBed模块中包括该服务:

describe('CustomComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ CustomComponent ],
     providers: [
        AuthService, BroadcastService, RoleService
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(CustomComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

测试组件时,应包括该组件使用的所有组件和服务。大多数时候,您不需要执行那些组件和服务的逻辑,事件和方法,并且可以模拟它们。查看有关如何模拟组件和服务的Angular文档:

© www.soinside.com 2019 - 2024. All rights reserved.