简体   繁体   English

使用 tick 和 fakeAsync 单元测试 Observable 的角度组件

[英]Unit Test angular component for Observable using tick and fakeAsync

I see questions very similar to this already been asked multiple times but no where I found exact solution or there are a lot of solution which confuses like me who has recently started with angular.我看到与此非常相似的问题已经被问过多次,但没有找到确切的解决方案,或者有很多解决方案让像我这样最近开始使用 angular 的人感到困惑。

I have an angular component like this:我有一个像这样的角度组件:

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;
       });

  }

}

I tried Spying the method getTestOutputList but I do not know how i can pass the argument for the method getTestOutputList to spyOn.我尝试监视方法 getTestOutputList 但我不知道如何将方法 getTestOutputList 的参数传递给 spyOn。 And further how i can test the observable.以及我如何测试可观察的。

There are different ways you could approach this.有不同的方法可以解决这个问题。 I typically like to use a spy object since that lets me set up the spy for a particular service and a return value for testing in one step.我通常喜欢使用 spy 对象,因为这让我可以在一个步骤中为特定服务设置 spy 和用于测试的返回值。

There were many errors in your code (such as missing 'this.' in front of your call to 'testService.getTestOutputList()', spelling 'takeUntil' wrong, setting isLoading to type of 'false' instead of to a boolean, etc) so I assume you did not copy and paste from working code.您的代码中有很多错误(例如在您调用“testService.getTestOutputList()”之前缺少“this.”、拼写“takeUntil”错误、将 isLoading 设置为“false”类型而不是布尔值等) 所以我假设你没有从工作代码中复制和粘贴。 :) :)

Nevertheless, I corrected the errors and put the code into a StackBlitz to demonstrate how a component such as this could be tested.尽管如此,我纠正了错误并将代码放入StackBlitz以演示如何测试这样的组件。 From that Stackblitz, here is the describe which includes a spy on the service and a test to show that the subscribe of the Observable is working.从那个 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']);
  });

});

As you can see in the StackBlitz, all the tests are passing.正如您在 StackBlitz 中看到的,所有测试都通过了。 I hope this helps.我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angular 使用 fakeAsync 进行单元测试,并且不等待代码使用 Observable 执行 - Angular unit test with fakeAsync and tick not waiting for code to execute with Observable 我正在使用 fakeAsync 并在 angular 的单元测试用例中打勾,但仍然在队列中出现错误 2 定期计时器 - I am using fakeAsync and tick in unit test case of angular , getting error 2 periodic timer(s) still in the queue 包含FileReader.onload的角度单元测试不适用于async / whenStable或fakeAsync / tick - Angular Unit Test including FileReader.onload doesn't work with async/whenStable nor fakeAsync/tick Angular 2 fakeAsync 在使用 tick() 的函数中等待超时? - Angular 2 fakeAsync waiting for timeout in a function using tick()? Angular 2组件中的单元测试“成功”和“错误”可观察响应 - Unit test 'success' and 'error' observable response in component for Angular 2 Angular - 无法进行 int 单元测试来模拟可观察的组件 - Angular - Unable int unit test to mock a component observable 角度测试:tickAsync块中的滴答vs刷新 - Angular testing: tick vs flushMicrotasks in fakeAsync block Angular 7 - 订阅 observable 的单元测试 - Angular 7 - Unit test for an observable with subscribe angular 2+ 中可观察的单元测试 - Unit test for observable in angular 2+ Angular 单元测试 observable 已返回 - Angular unit test observable was returned
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM