我正在尝试为使用 Observable.forkJoin 的组件方法编写测试。我已经在网上到处找了一些弹珠兔子洞,但最后我认为我真正需要做的就是模拟 Observable forkJoin 调用并返回假数据。这是我的组件方法
public loadData(): void {
this.someOtherMethod();
this.someProperty = false;
this.someOtherMethod2();
if (this.isNew) {
this.noData = true;
} else if (this.key) {
Observable.forkJoin([
/*00*/ this.service1$.someCall(this.key),
/*01*/ this.service2$.someCall(this.key),
/*02*/ this.service2$.someCall1(this.key),
/*03*/ this.service2$.someCall2(this.key),
/*04*/ this.service2$.someCall3(this.key),
/*05*/ this.service2$.someCall4(this.key),
/*06*/ this.service2$.someCall5(this.key),
])
.takeWhile(() => this.alive)
.subscribe(
response => {
... // join all the data together
},
// error => this.handleError(error)
);
}
this.changeDetector$.markForCheck();
}
到目前为止,这是我的测试:
it('makes expected calls', async(() => {
const response = [];
const service1Stub: Service1 = fixture.debugElement.injector.get(Service1 );
const service2Stub: Service2 = fixture.debugElement.injector.get(Service2 );
comp.key = key;
spyOn(comp, 'someOtherMethod').and.returnValue(of(response));
spyOn(comp, 'someOtherMethod2').and.returnValue(of(dummyData));
spyOn(service1Stub, 'someCall').and.returnValue(of(dummyData));
spyOn(service2Stub, 'someCall').and.returnValue(of(response));
spyOn(service2Stub, 'someCall1').and.returnValue(of(response));
spyOn(service2Stub, 'someCall2').and.returnValue(of(response));
spyOn(service2Stub, 'someCall3').and.returnValue(of(response));
spyOn(service2Stub, 'someCall4').and.returnValue(of(response));
spyOn(service2Stub, 'someCall5').and.returnValue(of(response));
comp.loadData();
expect(comp.someProperty).toBe(false);
expect(comp.someOtherMethod).toHaveBeenCalled();
expect(comp.someOtherMethod2).toHaveBeenCalled();
expect(service1Stub.someCall).toHaveBeenCalledWith(key);
expect(service2Stub.someCall1).toHaveBeenCalledWith(key);
expect(service2Stub.someCall2).toHaveBeenCalledWith(key);
expect(service1Stub.someCall3).toHaveBeenCalledWith(key);
expect(service1Stub.someCall4).toHaveBeenCalledWith(key);
expect(service1Stub.someCall5).toHaveBeenCalledWith(key);
}));
我收到以下错误(在我注释掉上面的错误捕获之后):
TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
Marbles 似乎关心测试 observable 以及它如何反应。我只是想看看调用是否正在进行,并对所有数据连接在一起的订阅内部发生的情况进行更深入的测试。
我知道有更好的方法来处理数据,但这需要对应用程序进行大修。我不能改变方法,只能忍受现在的样子。