我正在测试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
的同一个实例,但此测试仍然通过。我不理解的是什么?
答案 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