Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Karma - ngrx - No provider for Store

In one of my unit tests, I'm trying to mock @ngrx/store. I've used the technique successfully in another spec file, but when trying to use it in this one, I'm getting an injection error saying No provider for Store! Below is the relevant code from the spec file:

beforeEach(async(() => {
  const emptyState = { opportunities: { list: { items: [], page: 1, total: 0 } } };
  const mockStore = new MockStore<MockAppState>(emptyState);

  TestBed.configureTestingModule({
    declarations: [
      OpportunityListComponent,
      FilledArrayPipe
    ],
    imports: [
      NgFilterListModule,
      FormsModule
    ],
    providers: [
      { provide: OpportunityApi, useValue: apiStub },
      { provide: Store, useValue: mockStore },
      { provide: Router, useValue: routerStub }
    ]
  }).compileComponents();
}));

beforeEach(() => {
  store = fixture.debugElement.injector.get('Store');
});

The only difference between this component and the one that successfully uses the MockStore class is that this component is lazy loaded in its own module separate from AppModule. However, I tried importing StoreModule in that module as well as including StoreModule in the TestBed imports, both to no avail.

like image 883
jump_spider Avatar asked Oct 11 '17 11:10

jump_spider


3 Answers

You should add

 imports: [
  ...,
 StoreModule.forRoot(fromRoot.reducers),
],

That might help you

like image 194
Sobol Roman Avatar answered Nov 17 '22 06:11

Sobol Roman


Turns out my problem was I quoting Store in the fixture.debugElement.injector.get('Store') call. Removing the quotes fixed my problem.

like image 5
jump_spider Avatar answered Nov 17 '22 05:11

jump_spider


With NgRx 7 +, use the MockStore like this:

const initialState = {};
  
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [LogsNewComponent],
      providers: [
        provideMockStore({ initialState }),
      ],
    }).compileComponents();
  }));
like image 4
Yair Cohen Avatar answered Nov 17 '22 05:11

Yair Cohen