问题描述
我有一个组件,我每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 (将#修改为@)