9
votes

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.

3

3 Answers

6
votes

You should add

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

That might help you

5
votes

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

4
votes

With NgRx 7 +, use the MockStore like this:

const initialState = {};
  
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [LogsNewComponent],
      providers: [
        provideMockStore({ initialState }),
      ],
    }).compileComponents();
  }));