Search code examples
angularngrx-store

Getting error "NullInjectorError: No provider for SignalStore!" when attempting to unit test ng/rx Signal store


I have just used the Ng/Rx signal store for the first time.

 "@ngrx/signals": "^18.1.1",

I have it all working fine, and wanted to add some unit tests, following this documentation

The one difference is my Signal store does NOT use { providedIn: 'root' }, as I want to private separate instances in each component instance.

So I declare it is such

enter image description here

and then provide it in the component...

enter image description here

All works fine.

So, I have setup my spec file as follows....

 TestBed.configureTestingModule({
   providers: [      
     EquipmentFiltersItemStore, // <- provide the store here
     { provide: Logger, useClass: LoggerMock },
     { provide: TranslateService, useClass: TranslateMock },
     { provide: ReferenceDataService, useValue: refDataServiceSpy },       
   ]
 });

However, the first test, I get a null injector error...

enter image description here

Error details are

enter image description here

Anyone know what I am missing?


Solution

  • For anyone else that has this issue, I should have looked at the doco more carefully at this topic.

    So, you need to add all the provider inside each test, i.e. inside each 'it', or I think even better, I found we can just include them in the beforeEach

    e.g. the following now work fine for me...

     beforeEach(() => {
       dataStoreServiceSpy = jasmine.createSpyObj<DataStorageService>(
         'dataStorageService',
         ['getString']);
    
       TestBed.configureTestingModule({
          providers: [
          EquipmentFiltersItemStore,
          { provide: Logger, useClass: LoggerMock },
          { provide: TranslateService, useClass: TranslateMock },        
          { provide: DataStorageService, useValue: dataStoreServiceSpy },        
      ]
     });
    });
    
    it('should should return filter types on initialisation', () => {
      const store = TestBed.inject(EquipmentFiltersItemStore);
      store.filterTypes().length > 0;
      });
    });