我正在尝试测试使用其他服务的组件。我想通过为服务提供模拟来隔离组件。在 RC5 之前,我可以简单地使用addproviders
它现在已弃用并将被下一个 RC 删除。相反,我必须使用TestBed
. 当我出于某种原因提供模拟角度时,请继续寻找模拟所依赖的服务。并抛出一个DI exception
. 当我提供所有依赖项时,测试工作,但我不想为每个测试套件重复自己。这打破了基本的面向对象原则。我的测试套件:
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, useClass: DummyRestApiTestService},
// ]);
});
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();
}
));
});
角 2.0.0-RC5