简体   繁体   中英

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.

You should add

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

That might help you

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

With NgRx 7 +, use the MockStore like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM