Angular 4中的测试服务,作为setTimeout

时间:2017-07-05 07:09:03

标签: angular unit-testing karma-jasmine

我有一个服务,其中使用Injector注入了一些依赖项(我已经继承了此代码,暂时无法更改初始化),使用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但是当我测试这个时,调用setTimeout后调用TestInExecution-> mymethod并出错

TypeError: Cannot read property 'url' of undefined因为Router未实例化。

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

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');
            });
        });
    })));

1 个答案:

答案 0 :(得分:0)

在Angular documentation中,他们使用存根来交换路由器。你能不这样做吗?

检查出testing / router-stubs.ts here