首页 > 解决方案 > 使用 tick 和 fakeAsync 对 Observable 进行单元测试角度组件

问题描述

我看到与此非常相似的问题已经被多次问过,但我没有找到确切的解决方案,或者有很多解决方案让像我这样最近开始使用 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。以及我如何测试可观察的。

标签: angularunit-testingjasminekarma-jasmine

解决方案


有不同的方法可以解决这个问题。我通常喜欢使用 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 中看到的,所有测试都通过了。我希望这有帮助。


推荐阅读