【问题标题】:Is there a way to test Observable subscription in Angular?有没有办法在 Angular 中测试 Observable 订阅?
【发布时间】:2021-12-29 13:24:33
【问题描述】:

我是 Angular 新手,正在尝试为以下函数编写单元测试用例。

HomeComponent.ts

 ngOnInit() {
    this.msalBroadcastService.inProgress$
      .pipe(
        filter((status: InteractionStatus) => status === InteractionStatus.None),
        takeUntil(this._destroying$)
      )
      .subscribe(() => {
        this.YesNo = [
          { label: 'Yes', value: 'Yes' },
          { label: 'No', value: 'No' },
        ];
 
        this.cols = [
          { field: 'Human', header: 'name', width: '5' },
          { field: 'MaritalStatus', header: 'Marital Status', width: '8' },
      ];
        this.getAllAccounts();
      });
  }

我尝试了以下测试用例,但我不确定如何涵盖 YesNocolsgetAllAccounts()

HomeComponent.spec.ts

class MockUserService {
    inProgress = of("Login");
  }
  describe('AccountComponent', () => {
    let UserService;
    let comp;
    let userService;
    let testInteractionStatus: InteractionStatus.None;
    beforeEach(() => {
      TestBed.configureTestingModule({
        providers: [
          {
            provide: UserService,
            useClass: MockUserService
          },
          MsalService,
          MsalGuard,
          MsalBroadcastService,
          MessageService,
          HomeService,
          HomeComponent
      ],
        imports: [HttpClientTestingModule, RouterTestingModule],
        declarations: [
            HomeComponent
        ],
      }).compileComponents();
    });
  it('should test....', () => {
    const fixture = TestBed.createComponent(HomeComponent);
    const app = fixture.debugElement.componentInstance;
    app.ngOnInit();
    fixture.detectChanges();
    expect(userService.inProgress.YesNo).toBeDefined();
    expect(userService.inProgress.YesNo).toBeDefined();

  });
  • 角度版本

Angular CLI:12.2.6 节点:14.17.6 包管理器:npm 7.23.0 操作系统:darwin x64

【问题讨论】:

  • 模拟订阅还是测试订阅?嘲讽,看来你已经在为 userService 做了吧?
  • 您要测试订阅是否完成,还是要在收到值后立即测试结果?如果我是你,我会用专门的方法提取订阅块中的代码,让测试更容易
  • @SrikarPhaniKumarMarti 我正在测试订阅,但它没有按预期工作。我也尝试过模拟,但它仍然没有用。感谢这里的任何帮助。我收到类似“预期未定义要定义的错误。错误:“预期未定义要定义”
  • 您能否将订阅响应发送给我?我一看到就可以帮你
  • 我可以知道如何捕获订阅响应吗? @SrikarPhaniKumarMarti

标签: angular unit-testing jasmine testbed


【解决方案1】:

您可以使用类似 npm 的 rxjs-marblesjasmine-marbles 来测试从您的 observable 发出的不同值。

在测试套件中,您可以订阅您的 observable。一旦 observable 发出,你会这样做:

expect(component.yesNo).toHaveLength(2) // this is pseudo code, actual code may vary

请注意,当前您正在测试 home 组件,但在 home 组件的测试中,期望服务设置一些内容。单元测试是关于隔离外部依赖项,以便您只测试组件本身。

所以你不期望服务价值是什么。相反,您模拟服务并期望组件值是某种东西。

关于测试getAllAccounts(),您将创建一个间谍并期望它已被调用。

【讨论】:

  • 能否分享一个示例代码sn-p来试试?
【解决方案2】:

@itgeek,您可以执行以下操作来捕获订阅响应:

ngOnInit() {
    this.msalBroadcastService.inProgress$
      .pipe(
        filter((status: InteractionStatus) => status === InteractionStatus.None),
        takeUntil(this._destroying$)
      )
      .subscribe((data: any) => { <<< ADD THIS LINE >>>
        console.log('Subscription Response ==>', data); << ADD THIS LINE >>
        this.YesNo = [
          { label: 'Yes', value: 'Yes' },
          { label: 'No', value: 'No' },
        ];
 
        this.cols = [
          { field: 'Human', header: 'name', width: '5' },
          { field: 'MaritalStatus', header: 'Marital Status', width: '8' },
      ];
        this.getAllAccounts();
      });
  }

在控制台中执行此操作后,您应该能够看到响应

【讨论】:

  • 感谢我找到了解决问题的方法。
猜你喜欢
  • 2017-03-24
  • 1970-01-01
  • 2018-09-08
  • 1970-01-01
  • 2018-03-31
  • 2020-09-15
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
相关资源
最近更新 更多