NullInjectorError: No provider for Store

21,444

Solution 1

if your service is referencing an ngrx store then you need to import the ngrx modules. I am making an assumption right now that you are doing that in your AppModule. You need to duplicate that in your TestBed module. I generally create a test ngrx module that does all that and then I can just import that in any spec file that references Store

Solution 2

As stated here

Add following to the specs.ts file:
// Add the import the module from the package 
import { StoreModule } from '@ngrx/store';

   // Add the imported module to the imports array in beforeEach 
   beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        StoreModule.provideStore({})
      ],
      declarations: [
        // The component that's being tested
      ]
    })
    .compileComponents();
  }));

And if you get error Property 'provideStore' does not exist on type 'typeof StoreModule use forRoot instead of provideStore. Also look here and here is similar question here.

Cheers!

Solution 3

You can use the ngrx mock store:

import { provideMockStore } from '@ngrx/store/testing';

beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [provideMockStore({})],
    });
  });

You can define a specific state and pass it as method parameter.

Share:
21,444
Kode_12
Author by

Kode_12

Updated on October 18, 2020

Comments

  • Kode_12
    Kode_12 over 3 years

    I'm receiving the following error when running my unit tests:

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

    Here is the code in my test file:

    import { TestBed, inject } from '@angular/core/testing';
    
    import { BlogService } from './blog.service';
    
    describe('BlogService', () => {
      beforeEach(() => {
        TestBed.configureTestingModule({
          providers: [BlogService]
        });
      });
    
      it('should be created', inject([BlogService], (service: BlogService) => {
        expect(service).toBeTruthy();
      }));
    });
    

    I'm not sure why this error is occuring. I thought the 'inject' call instantiates the service.