【问题标题】:Test Broadcast Service测试广播服务
【发布时间】:2019-11-14 15:22:42
【问题描述】:

您好,我正在尝试为带有 observable 的组件编写 Angular 代码,但我无法测试广播服务。我收到一条错误消息,提示未调用该服务。我应该如何访问该服务?任何帮助,将不胜感激。谢谢。

这是我的可观察组件:

  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('AppComponent', () => {
      beforeEach(() => {
       TestBed.configureTestingModule({
         imports: [RouterTestingModule],
         declarations: [AppComponent],
         providers: [WindowService, HttpClient, RoleService, UserService, HttpHandler, BroadcastService, MsalService,
        {
          provide: MSAL_CONFIG,  // MsalService needs config, this provides it.
          useFactory: () => ({   // Note this is an arrow fn that returns the config object
            redirectUri: window.location.origin + '/',
            clientID: mockData.clientID,
          }),
        }],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    }).compileComponents();
  });

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

    it("Role should be Data Steward", fakeAsync (() => {
    const fn = 'msal:acquireTokenSuccess';
    const subscription = new Subscription();
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    const spyOnBS = spyOn(app.broadcastService,'subscribe');
    const roleServiceCall = 
    spyOn(app.roleService,'checkServerEventReviewers');
    app.ngOnInit();
    tick();
    fixture.whenStable().then(() => {
      expect(spyOnBS).toHaveBeenCalled();
      expect(roleServiceCall).toHaveBeenCalled();
});
}));

【问题讨论】:

标签: angular unit-testing testing angular7 msal


【解决方案1】:

对不起,我读错了这个问题。 (响应更新)。 我认为问题在于您正在测试可观察的服务。我认为你应该使用fakeAsynctick 来测试它。

    describe('AppComponent', () => {
      beforeEach(() => {
       TestBed.configureTestingModule({
         imports: [RouterTestingModule],
         declarations: [AppComponent],
         providers: [WindowService, HttpClient, RoleService, UserService, HttpHandler, BroadcastService, MsalService,
        {
          provide: MSAL_CONFIG,  // MsalService needs config, this provides it.
          useFactory: () => ({   // Note this is an arrow fn that returns the config object
            redirectUri: window.location.origin + '/',
            clientID: mockData.clientID,
          }),
        }],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    }).compileComponents();
  });

  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', fakeAsync(() => {
      const {app} = setup();
      spyOnBS = spyOn(app.broadcastService,'subscribe');
      spyOn(app.authService, 'getUser').and.returnValue(mockData.userDetails);
      spyOn(app.authService, 'acquireTokenSilent').and.returnValue('msal:acquireTokenSuccess');
      app.ngOnInit();
      tick();
      fixture.detectChanges();
      fixture.whenStable().then(() => {
          expect(spyOnBS).toHaveBeenCalled();
      });
    ));

试试看是否可行。

【讨论】:

  • 我确实将它包含在测试台模块中。我只是没有将那部分代码添加到我的问题中。它仍然没有运行
  • 你能把spec文件的所有内容都加进去吗?
  • 完成!我以为它没有被调用,因为它在 subscription.add 内,但我不太确定
  • 谢谢,我想我找到了问题所在。我刚刚更新了我的答案。
  • 成功了!!非常感谢。我可以要求您再澄清一下吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-13
  • 2019-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多