我正在尝试测试使用其他服务的组件.我想通过为服务提供模拟来隔离组件.在RC5之前,我可以简单地使用现在已弃用的addproviders,并将被下一个RC删除.相反,我必须使用TestBed.当我因某种原因提供模拟角度时,请继续寻找模拟所依赖的服务.并抛出DI异常.当我提供所有依赖项时,测试工作但我不想为每个测试套件重复自己.这打破了基本的OO原则.
我的测试套件:
我的测试套件:
describe('Component: DummyRestApi',() => { class DummyRestApiTestService { GetAll() { return Rx.Observable.create(observer => { let data:Data[] = []; data.push({ id: 0,data: 'data' }); observer.next(data); observer.complete(); }); } Add(data) { } } let fixture; let myMockWindow:Window; // ToDo use the mocks beforeEach(() => { myMockWindow = <any> {location: <any> {hostname: '127.0.0.1'}}; TestBed.configureTestingModule({ declarations: [DummyRestApiComponent],providers: [ // ServerAddressResolverService,DummyRestApiComponent,// ConfigurationService,{provide: DummyRestApiService,useClass: DummyRestApiTestService},// {provide: Window,useValue: myMockWindow} ],imports: [FormsModule,HttpModule] }); TestBed.compileComponents().catch(error => console.error(error)); // addProviders([ // DummyRestApiComponent,// {provide: DummyRestApiService,// ]); }); describe('Initializing',() => { beforeEach(async(() => { console.log('Compiling'); TestBed.compileComponents().catch(error => console.error(error)); console.log('Compiling again'); })); it('should create an instance',async(() => { var fixture = TestBed.createComponent(DummyRestApiComponent); fixture.detectChanges(); expect(fixture.debugElement.componentInstance).toBeTruthy(); } )); });
Angular 2.0.0-RC5
请注意,Patrick Ineichens回答使用了提议,已弃用.
原文链接:https://www.f2er.com/angularjs/143883.htmlproviders: [provide(TodoService,{ useValue: this.service })]
应改为:
providers: [{provide:TodoService,useValue: this.service }]