使用tick和fakeAsync进行可观察的单元测试角度分量

时间:2019-03-06 09:55:35

标签: angular unit-testing jasmine karma-jasmine

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

我有一个像这样的角度分量:

exportClass 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。进一步说明如何测试可观察的物体。

1 个答案:

答案 0 :(得分:0)

您可以采用不同的方法来解决此问题。我通常喜欢使用间谍对象,因为这样可以让我为特定服务设置间谍,并一步就可以为测试设置返回值。

您的代码中存在许多错误(例如,在调用“ 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中看到的那样,所有测试都通过了。我希望这会有所帮助。

相关问题