微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

对组件进行角度测试,该组件每2秒进行一次API调用,并重复多达x次,直到找到记录为止

如何解决对组件进行角度测试,该组件每2秒进行一次API调用,并重复多达x次,直到找到记录为止

我有一个组件,我每2秒重复进行一次API调用,并且当响应包含名称为“ somename”的记录时,我将通过调用unsubscribe来停止循环。直到找到所需的记录,然后继续循环播放,直到 我达到了mazRetries计数=120。这是我的组件代码, 这样做:

ngOnit() {
    this.retryCount = 0;
    this.maxRetries = 120;
    const source = interval(2000);
    this.subscription = source.subscribe(val => this.poll());
  }

  poll() {
    if (this.retryCount > this.maxRetries) {
      this.subscription.unsubscribe();
      return;
    }
    const myList = this.service.getRecords();
    console.log('myList = ' + myList);   // prints undefined when running my test below
    if (myList.length > 0) {
      const rec = myList.filter(v => v.name === 'somename');
      if (rec.length > 0) {
        window.location.href = rec.pop().url;   // redirect to an external url
        this.subscription.unsubscribe();
        return;
      }
    }
    this.retryCount++;
  }

现在,我很难测试上面的代码。首先,当将此代码包装在计时器中时,下面的我用spyOn(myService,'getRecords').and.callFake(() => records.slice())返回一些模拟日期的spyOn似乎不起作用。 我总是使用这种样式来模拟对API调用的响应,该API调用可以正常工作,但是当该调用在interval(2000).subscriber(.....)内运行时,它将无法正常工作,并且响应未定义。我不确定如何修改测试代码,以使其正确返回模拟的响应,而不是未定义的响应。

另外,就我而言,当找到我要查找的记录时,我只是重定向一个外部URL。对于测试而言,这是一个问题,因为一旦转到外部网址,它就会停止。有没有一种方法可以通过模拟此调用或其他方法解决此问题?

describe('MyComponent',() => {
  ..
  ..
  let myService;
  beforeEach(async(() => {
    Testbed.configureTestingModule({
      declarations: [ MyComponent ],imports: [ UIRouterTestingModule ],providers: [
       MockMyServiceProvider
       ..
       ..
      ],})
      .compileComponents();

    let records = [{
      "name": "somename","first": "firstname","last": "lastname"
    }];

    myService = Testbed.inject(MyService);
    spyOn(myService,'getRecords').and.callFake(() => records.slice());

  }));
  
  beforeEach(() => {
    fixture = Testbed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('component should be created',() => {
    expect(component).toBeTruthy();
  });

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。