本文介绍了在 RxJS 5.5 中测试和模拟可出租操作符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在lettable operator之前,我做了一个helper来修改debounceTime方法,所以它使用了一个TestScheduler:

Before lettable operator, I did a helper to modify debounceTime method, so it uses a TestScheduler:

export function mockDebounceTime(
    scheduler: TestScheduler,
    overrideTime: number,
): void {
    const originalDebounce = Observable.prototype.debounceTime;

    spyOn(Observable.prototype, 'debounceTime').and.callFake(function(
        time: number,
    ): void {
        return originalDebounce.call(
            this,
            overrideTime,
            scheduler,
        );
    });
}

因此对以下 Observable 的测试很简单:

So the test of the following Observable was easy:

@Effect()
public filterUpdated$ = this.actions$
    .ofType(UPDATE_FILTERS)
    .debounceTime(DEFAULT_DEBOUNCE_TIME)
    .mergeMap(action => [...])

使用可出租的操作符,filterUpdated$ Observable 是这样写的:

With lettable operators, the filterUpdated$ Observable is written like that:

@Effect()
public filterUpdated$ = this.actions$
    .ofType(UPDATE_FILTERS)
    .pipe(
        debounceTime(DEFAULT_DEBOUNCE_TIME),
        mergeMap(action => [...])
    );

我再也无法修补 debounceTime 运算符了!如何将 testScheduler 传递给 debounceTime 运算符?

I cannot patch the debounceTime operator anymore ! How can I pass the testScheduler to the debounceTime operator ?

推荐答案

您可以使用接受自定义调度程序的第二个参数.

You can use the second argument that accepts a custom Scheduler.

  debounceTime(DEFAULT_DEBOUNCE_TIME, rxTestScheduler),

所有代码

import { Scheduler } from 'rxjs/scheduler/Scheduler';
import { asap } from 'rxjs/scheduler/asap';

@Injectable()
export class EffectsService {
  constructor(private scheduler: Scheduler = asap) { }

  @Effect()
  public filterUpdated$ = this.actions$
    .ofType(UPDATE_FILTERS)
    .pipe(
        debounceTime(DEFAULT_DEBOUNCE_TIME, this.scheduler),
        mergeMap(action => [...])
    );
}

然后测试

describe('Service: EffectsService', () => {
  //setup
  beforeEach(() => TestBed.configureTestingModule({
    EffectsService,
    { provide: Scheduler, useValue: rxTestScheduler} ]
  }));

  //specs
  it('should update filters using debounce', inject([EffectsService], service => {
    // your test
  });
});

这篇关于在 RxJS 5.5 中测试和模拟可出租操作符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 04:27