简体   繁体   English

Angular2 TestBed注入

[英]Angular2 TestBed Inject

I'm testing a service ( myService ) in Angular 2 that has a dependency on Router . 我正在Angular 2中测试一个对Router依赖的服务( myService )。 Since I'm using one of Angular's components, I'm going to use Angular's TestBed class. 由于我使用的是Angular的组件之一,因此我将使用Angular的TestBed类。 So I set up my beforeEach as follows: 所以我将我的beforeEach设置如下:

let router: Router;
beforeEach(async(() => {
        TestBed.configureTestingModule({
            providers: [
                {provide: Router, useClass: RouterStub}
            ]
        });
        router = TestBed.get(Router);
        myService = new MyService(router);
    }));

where RouterStub is defined as 其中RouterStub定义为

@Injectable()
export class RouterStub {
    navigate() {};
}

Now I write my test to fail (red, green, refactor... ) 现在,我编写测试失败(红色,绿色,重构...)

it('on myServiceMethod calls router', () => {    
    let spy = spyOn(router, 'navigate');

    // myService.myServiceMethod(); // commented out so test fails

    expect(spy).toHaveBeenCalledTimes(1);
})

and the test fails as expected. 并且测试按预期失败。 However, I now try and write the same test using the TestBed Inject function, ie, 但是,我现在尝试使用TestBed Inject函数编写相同的测试,即

it('on myServiceMethod calls router', () => {
    inject([Router], (router: Router) => {
        let spy = spyOn(router, 'navigate');

       // myService.myServiceMethod(); // commented out so test fails

        expect(spy).toHaveBeenCalledTimes(1);
    })   
})

and this test passes even though I thought the Inject function would retrieve the same instance of Router from the TestBed . 即使我认为Inject函数将从TestBed检索到Router的相同实例,此测试仍通过。 What am I not understanding? 我不明白什么?

配合它,您应该使用@angular/core/testing getTestBed并将其注入,

  getTestBed().get(YourService)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM