大佬教程收集整理的这篇文章主要介绍了unit-testing – 运行Angular2测试,调用setTimeout错误,“不能在异步区域测试中使用setInterval”,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我的窗口小部件从其ngOnInit方法请求数据,并在发出请求时发出加载指示符.我的模拟服务在1ms后返回一些数据.
这是一个暴露问题的简化版本
import { inject,async,TESTComponentBuilder,ComponentFixturE} from '@angular/core/tesTing'; import {http,Headers,requestOptions,Response,http_PROVIDERS} from '@angular/http'; import {provide,Component} from '@angular/core'; import {ObservablE} from "rxjs/Rx"; class Myservice { constructor(private _http: http) {} getData() { return this._http.get('/some/rule').map(resp => resp.text()); } } @Component({ template: `<div> <div class="loader" *ngIf="_isLoading">Loading</div> <div class="data" *ngIf="_data">{{_data}}</div> </div>` }) class FakeComponent { private _isLoading: Boolean = false; private _data: String = ''; constructor(private _service: MyservicE) {} ngOnInit() { this._isLoading = true; this._service.getData().subscribe(data => { this._isLoading = false; this._data = data; }); } } describe('FakeComponent',() => { var service = new Myservice(null); var _fixture:ComponentFixture<FakeComponent>; beforeEach(async(inject([TESTComponentBuilder],(tcb:TESTComponentBuilder) => { return tcb .overrideProviders(FakeComponent,[ http_PROVIDERS,provide(Myservice,{useValue: servicE}),]) .createAsync(FakeComponent) .then((fixture:ComponentFixture<FakeComponent>) => { _fixture = fixture; }); }))); it('Shows loading while fetching data',(cb) => { // Make the call to getData take one ms so we can verify its state while the request is pending // Error occurs here,when the widget is initialized and sends out an XHR spyOn(service,'getData').and.returnValue(Observable.of('value').delay(1)); _fixture.detectChanges(); expect(_fixture.nativeElement.querySELEctor('.loader')).toBeTruthy(); // Wait a few ms,should not be loading // This doesn't seem to be the problem setTimeout(() => { _fixture.detectChanges(); expect(_fixture.nativeElement.querySELEctor('.loader')).toBefalsy(); cb(); },10); }); });
这在Angular2 rc1中运行正常,它会在rc4中引发错误,有什么建议吗?
此外,如果直接从测试本身使用setTimeout,则没有错误
fit('lets you run timeouts',async(() => { setTimeout(() => { expect(1).toBe(1); },10); }));
我的解决方案是自己实现这条线,考虑到问题中发布的另一个例子确实有效,这几乎是有意义的.
// This is what we should be doing,but somehow,it isn't working. // return Observable.of(result).delay(0)); function createDelayedObservable <T>(result:any,time:number = 0):Observable<T> { return new Observable<T>(observer => { setTimeout(() => observer.next(result),timE); }); }
但是,我仍然不明白为什么下面没有失败,所以我不接受我自己的答案,希望对区域有深刻理解的人能告诉我发生了什么.
it('should be able to use delay in tests',(cb) => { var obs = Observable.of(1).delay(0); obs.subscribe(val => { expect(val).toBe(1); cb() }); });
以上是大佬教程为你收集整理的unit-testing – 运行Angular2测试,调用setTimeout错误,“不能在异步区域测试中使用setInterval”全部内容,希望文章能够帮你解决unit-testing – 运行Angular2测试,调用setTimeout错误,“不能在异步区域测试中使用setInterval”所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。