我有一个Angular应用程序,当用Karma运行单元测试时,我得到一个错误,说组件中的Store存在缺少的提供程序 . 存储不是直接注入组件,而是注入到组件中的服务 .
如果我将StoreModule导入组件,则错误消失,但我不应该这样做,因为组件不直接需要存储 .
错误:
错误:StaticInjectorError(DynamicTestModule)[StoreRootModule - > Store]:StaticInjectorError(Platform:core)[StoreRootModule - > Store]:NullInjectorError:没有Store的提供者!
零件
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);
});
}
1 回答
如果您在任何其他模块中使用任何组件,提供程序,则需要在导入下导入该特定模块,
否则它将找不到特定的提供程序,它将抛出错误 . 上述问题很常见 . 要解决它导入模块 .