Search code examples
angularngxs

How to test NGXS in angular component?


I am new to NGXS and while testing I am getting error in all test cases. I am getting data from store: app.component.ts

    somedata: Idetail
    this.someData = this.store.selectSnapshot(State.details).
    this.data = this.someData.DATA;

But I am getting error on every single test case:

TypeError: Cannot read property 'DATA' of null


Solution

  • You have to mock the store to use it inside Tests.

    E.g.:

    beforeEach(async(() => {
       TestBed.configureTestingModule({
          declarations: [MyComponent]
          imports: [NgxsModule.forRoot([])] // import real module without state
       });
    
       const store:Store = TestBed.get(Store);
       spyOn(store, 'select').and.returnValue(of(null)); // be sure to mock the implementation here
       spyOn(store, 'selectSnapshot').and.returnValue(null); // same here
    }));