2017-07-05 34 views
0

我在其中有使用一些依赖注入服务的Injector(我继承了这个代码,并不能改变现在的初始化)使用setTimeout测试服务在角4,如setTimeout的

@Injectable 
export class MyService { 
router:Router; 
    constructor(private injector: Injector) { 
     setTimeout(() => { 
     debugger; 
     this.router = injector.get(Router); 
     }); 
    } 

    public myMethod(){ 
     const someString = this.router.url.slice(1,someLength); 
    } 
} 

我需要测试myMethod但是当过我测试这个setTimeoutTestInExecution-> mymethod后调用被调用,并给出了一个错误

TypeError: Cannot read property 'url' of undefinedRouter不是实例。

如何确保在执行测试之前正确注入路由器。

fit('Test My Service', fakeAsync(inject([Router, Location, MyService], 
    (_router: Router, _location: Location, myService: MyService) => { 
     let fixture = TestBed.createComponent(SomeComponent); 
     //Wait for component to Initialize 
     tick(500); 
     fixture.detectChanges(); 
     fixture.whenStable().then(() => { 
      _router.navigate(['/someCompoenet']).then(() => { 
       expect(myService.myMethod()).toBe('Some String'); 
      }); 
     }); 
    }))); 
+0

你为什么要使用超时注入在服务路由器? – Gambo

+0

有一个循环依赖关系,通过使用'injector'和'setTimeout'解决。看到这个:https://stackoverflow.com/a/41807414/756987 – Ankesh

回答

0

在角documentation他们使用存根换出路由器。你能不能那样做?

退房测试/路由器stubs.ts here