我有一个Angular应用程序,并且使用Karma运行单元测试时,我得到一个错误,指出组件中缺少商店的提供程序。 商店不是直接注入到组件中,而是注入到注入到组件中的服务中。
如果我将StoreModule导入组件,该错误消失,但是我不必这样做,因为该组件不需要直接存储。
错误:
错误:StaticInjectorError(DynamicTestModule)[StoreRootModule->存储]: StaticInjectorError(平台:核心)[StoreRootModule->存储]: NullInjectorError:没有商店的提供者!
组件
export class TestComponent {
constructor(private testService: TestService) {}
}
服务
@Injectable({
providedIn: 'root'
})
export class TestService {
constructor(private store: Store<AppState>) {}
}
组件单元测试
class MockTestService {
}
describe('TestComponent', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
let resetMemorablePhraseService: MockTestService;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [TestComponent],
imports: [
// StoreModule.forRoot({}) // adding this line gets rid of the error
],
providers: [{
provide: TestService, useClass: MockTestService
}]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
service = TestBed.get(TestService);
});
}
答案 0 :(得分:0)
如果要在其他模块中使用任何组件或提供程序,则需要在导入下导入该特定模块,
否则,它将找不到特定的提供程序,并且将引发错误。上面的问题很常见。要解决该问题,请导入模块。
答案 1 :(得分:0)
我找到了原因
如果父组件具有依赖于某些服务的子组件
还应将其添加到TestBed.configureTestingModule
示例:
child.component.ts
// ChildComponent has dependency to AnyService
@Component({
selector: 'app-child',
template: 'I have dependency from a service'
})
export class ChildComponent {
constructor(private anyService: AnyService) { }
}
parent.component.ts
// ParentComponent has no dependency from AnyService
// but since ChildComponent a.k.a "<app-child></app-child>" is embedded here,
// it will also be the dependency of this component
@Component({
selector: 'app-parent',
template: `
<h1>I don't have dependency from any service</h1>
<app-child></app-child>
`
})
export class ParentComponent { }
我希望这可以帮助所有遇到同样问题的读者