2

I have an Angular application and when running unit tests with Karma, I get an error in saying that there is a missing provider for the Store in a component. The store is not directly injected into the component, but into a service that is injected into the component.

If I import the StoreModule into the component, the error disappears, but I shouldn't have to do that as the component does not require the store directly.

Error:

Error: StaticInjectorError(DynamicTestModule)[StoreRootModule -> Store]: StaticInjectorError(Platform: core)[StoreRootModule -> Store]: NullInjectorError: No provider for Store!

Component

export class TestComponent {
    constructor(private testService: TestService) {}
}

Service

@Injectable({
    providedIn: 'root'
})
export class TestService {
    constructor(private store: Store<AppState>) {}
}

Component unit test

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);
    });
}
MartaGalve
  • 1,056
  • 3
  • 13
  • 34

2 Answers2

0

I found out the cause

If the parent component have a child component that has dependency to some service

It should need to be added to the TestBed.configureTestingModule as well

example:

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 { }

I hope this helps all readers out there having the same problem

aj go
  • 637
  • 2
  • 10
  • 27
-1

If you are using any component,provider inside any other module, you need to import that particular Module under imports,

Otherwise it will not find the particular provider and it will throw the error. The above problem is usual. To solve it import the Module.

Sajeetharan
  • 216,225
  • 63
  • 350
  • 396