Search code examples
angularkarma-jasminengrx

InitialState of Store with 2 reducers while testing a component


I am trying to test a component. It uses 2 different reducer states with Ngrx. How can I tell in the initialState of the test which one comes from AppState and the other comes from AdminState (LazyLoaded) please?

describe('UploadImageComponent', () => {
  let component: UploadImageComponent;
  let fixture: ComponentFixture<UploadImageComponent>;
  const initialState = {
    selectedPage: null,         // comes from AppState
    pages: [],                  // comes from AppState
    uploadLoading: false,       // comes from AdminState (LazyLoaded)
    thumbnailIsCreating: false  // comes from AdminState (LazyLoaded)
  };

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [UploadImageComponent],
      imports: [
        RouterTestingModule,
        AngularFireDatabaseModule,
        AngularFireModule.initializeApp(environment.firebase)
      ],
      providers: [
        PageDbService,
        AdminService,
        PagesService,
        provideMockStore({ initialState }),
      ]
    })
      .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(UploadImageComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

While running ng test, karma says :

TypeError: Cannot read property 'thumbnailIsCreating' of undefined

I think selectedPage and pages are well passed, but not the two others from AdminState. Is it because AdminState is lazyLoaded? Or maybe the initialState is wrong?


Solution

  • It's most likely your initialState is wrong.

    Download the Redux dev tools (https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd?hl=en, there is also a Firefox one) and see the structure of your store using that tool. This is how you configure it (https://ngrx.io/guide/store-devtools) and then you can do npm start and should see the structure of your store.

    I bet your initialState should be something like this:

    initialState = {
      selectedPage: null,         // comes from AppState
      pages: [],
      admin: {
          uploadLoading: false,       // comes from AdminState (LazyLoaded)
          thumbnailIsCreating: false
      }             
     
    }