【问题标题】:How to write Jasmine Test case for a subscribe block in ngOninit and pass some dummy data?如何在 ngOninit 中为订阅块编写 Jasmine 测试用例并传递一些虚拟数据?
【发布时间】:2020-08-15 16:57:26
【问题描述】:

我在 Angular 7 中第一次尝试 Jasmine 测试用例。我有一个 observable,它使用服务文件中的 next() 发出数据。组件订阅 observable 并使用数据。这是ngOnInit中的代码

ngOnInit() {
    this.loading = true;

    this.subscribe(this.advDirectService.directive$, data => {          
        this.directives = data;
        this.loading = false;
    });
    this.advDirectService.loadDirective(); }

我可以预期会调用 loadDirective。但是当我试图期待 this.directives 它总是说 NULL。我的组件扩展了 BaseComponent。请帮助我学习如何为订阅块内的代码编写测试。

【问题讨论】:

    标签: angular jasmine


    【解决方案1】:

    您需要将服务和组件的测试分开。单元测试旨在尽可能地隔离。

    而不是测试服务是否在组件中工作,您应该使用模拟数据,您可以像这样传递它并且只测试组件功能:

    it('should test something for the component', () => {
      component.directives = mockData;
    
      // run a function that depends on the data and expect a return result
    })
    

    另一方面,您需要测试服务,它是异步调用,您应该在服务 .spec.ts 文件中执行此操作:

    it('should test something in the service', (done) => {
      this.directive$.subscribe(data => {
        expect(data) ... something
        done();
      })
    })
    

    请注意,我们将 done 参数传递给回调 - 这表明异步测试已完成 - 否则测试将失败并出现超时错误。

    我应该警告您,异步测试可能很复杂:如果您希望第一次发出始终为空,您可能需要在订阅之前使用 pipe(skip(1))。

    还有其他测试 observables 的方法,例如大理石测试 - 但我个人还没有深入研究。

    【讨论】:

      【解决方案2】:

      应该是这样的:

      let dummy_data = "Some dummy data to be returned by service";
      const spyOnInit = spyOn(component, "ngOnInit").and.callThrough();
          advDirectService = TestBed.get(<Your Service Name>);
          const spyData = spyOn(advDirectService, "directive$")
            .and.returnValue(Observable.of(dummy_data));
          advDirectService.directive$().subscribe(
            success => {
              expect(success).toEqual(advDirectService);
            }
            , (error) => {
              expect(error).toBeTruthy();
            });
      
          component.ngOnInit();
          expect(component.ngOnInit).toHaveBeenCalled(); //write your expect statement here
          spyData.calls.reset();
          spyOnInit.calls.reset();
      

      【讨论】:

        猜你喜欢
        • 2021-10-15
        • 2019-04-16
        • 2018-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多