我正在尝试在 Angular 2 中测试我的组件,但是当组件的服务不在其提供程序中时,它会出现问题。
import {Component} from 'angular2/core';
import {ServiceName} from '../../services/ServiceName';
@Component({
selector: 'component-name',
template: `
<div></div>
`
})
export class ComponentName {
constructor(private ServiceName: ServiceName) {
}
}
这是我的测试:
import {ComponentName} from '<path>';
import {ServiceName} from '<path>';
import {
iit,
it,
ddescribe,
describe,
expect,
inject,
injectAsync,
TestComponentBuilder,
beforeEachProviders,
fakeAsync,
tick,
setBaseTestProviders
} from 'angular2/testing';
beforeEachProviders(() => [
ServiceName
]);
import {
TEST_BROWSER_PLATFORM_PROVIDERS,
TEST_BROWSER_APPLICATION_PROVIDERS
} from 'angular2/platform/testing/browser';
setBaseTestProviders(TEST_BROWSER_PLATFORM_PROVIDERS, TEST_BROWSER_APPLICATION_PROVIDERS);
describe('ServiceName', () => {
it('should have name property set', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
return tcb.createAsync(ComponentName).then((fixture) => {
fixture.debugElement.componentInstance.isPanelActive = true;
fixture.detectChanges();
var compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('a.yes')).toContainText('Something');
});
}));
});
我得到的错误是:
Failed: No provider for ServiceName! (ComponentName -> ServiceName)
Error: DI Exception
我尝试了 overrideProvide 方法,但它不起作用,还尝试在测试中创建一个 TestComponent 并将提供程序与 ComponentName 指令一起传递到那里。
有人有什么想法吗?是否不可能通过引导文件引导服务而不使用@Component 中的提供程序?我认为这就是 beforeEachProviders 的全部意义所在。