Angular2 TestBed注入

时间:2017-03-05 18:01:10

标签: angular jasmine testbed

我正在测试Angular 2中的服务(myService),该服务依赖于Router。由于我使用的是Angular的一个组件,我将使用Angular的TestBed类。所以我按如下方式设置beforeEach

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

其中RouterStub定义为

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

现在我把我的测试写成失败(红色,绿色,重构......)

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

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

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

并且测试按预期失败。但是,我现在尝试使用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);
    })   
})

虽然我认为Inject函数会从Router检索TestBed的同一个实例,但此测试仍然通过。我不理解的是什么?

1 个答案:

答案 0 :(得分:0)

配合你应该使用while (i < num) { if (num % i == 0) { array.push(i); } i++; // now i can be incremented regardless of the condition in the "if" block. } 中的getTestBed并将其注入,

@angular/core/testing