【问题标题】:Unit Test angular component for Observable using tick and fakeAsync使用 tick 和 fakeAsync 对 Observable 进行单元测试角度组件
【发布时间】:2019-03-06 09:55:35
【问题描述】:

我看到与此非常相似的问题已经被问过多次,但我没有找到确切的解决方案,或者有很多解决方案让像我这样最近开始使用 angular 的人感到困惑。

我有一个像这样的角度组件:

export class MyTestComponent implements OnInit {
  isLoading: false;
  testOutput: any = [];
  someConstant: string = "gvt";
  private unsubscription$ = new Subject();
  constructor(private testService: TestService){}

  ngOnInit() {
    getTestOutputList(this.someConstant);
  }

  getTestOutputList(someConstant){
    this.isLoading = true;

    testService.getTestOutputList(someConstant)
      .pipe(takeUnitl(this.unsubscription$))
      .subscribe(res => {
         this.isLoading = true;
         this.testOutput = res;
       });

  }

}

我尝试监视方法 getTestOutputList 但我不知道如何将方法 getTestOutputList 的参数传递给 spyOn。以及如何测试 observable。

【问题讨论】:

    标签: angular unit-testing jasmine karma-jasmine


    【解决方案1】:

    有不同的方法可以解决这个问题。我通常喜欢使用 spy 对象,因为它可以让我为特定服务设置 spy 并在一个步骤中为测试设置返回值。

    您的代码中有很多错误(例如在调用“testService.getTestOutputList()”之前缺少“this.”,拼写“takeUntil”错误,将 isLoading 设置为“false”类型而不是布尔值等),所以我假设您没有从工作代码中复制和粘贴。 :)

    尽管如此,我纠正了错误并将代码放入StackBlitz 以演示如何测试这样的组件。在 Stackblitz 中,这里是描述,其中包括对服务的间谍和测试,以表明 Observable 的订阅正在工作。

    describe('MyTestComponent', () => {
      let component: MyTestComponent;
      let fixture: ComponentFixture<MyTestComponent>;
      let service: TestService;
      const serviceSpy = jasmine.createSpyObj('TestService', {
        getTestOutputList : of(['the result'])
      });
    
      beforeEach(async(() => {
          TestBed.configureTestingModule({
            declarations: [MyTestComponent],
            providers: [ 
              { provide: TestService, useValue: serviceSpy }
            ]
          }).compileComponents().then(() => {
            service = TestBed.get(TestService);
            fixture = TestBed.createComponent(MyTestComponent);
            component = fixture.componentInstance;
          });
      }));
    
      it('should create', () => {
        expect(component).toBeTruthy();
      });
    
      it('should set this.testOutput properly if subscribe is working', () => {
        fixture.detectChanges(); // Need this here to execute ngOnInit()
        expect(component.testOutput).toEqual(['the result']);
      });
    
    });
    

    正如您在 StackBlitz 中看到的,所有测试都通过了。我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      • 1970-01-01
      • 2019-05-20
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多