Search code examples
angulartypescriptunit-testingngrx

Angular Unit Testing - Cannot read properties of undefined (reading 'size') NgRx


I get an error about my spec file unit test without success to solve, the error display when I run npm test, on karma chrome:

enter image description here

agent.service.spec.ts:

import { HttpClientTestingModule } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { MemoizedSelector, Store } from '@ngrx/store';
import { MockStore, provideMockStore } from '@ngrx/store/testing';
import * as fromGrid from './../grid/store/grid.reducer';

import { GridActions } from './../grid/store/grid.actions';
import { AgentService } from './agent.service';
import { GridSizeEnum } from '../models/enums/GridSize';


describe('AgentService', () => {

    let agentService: AgentService;
    let mockStore: MockStore<fromGrid.State>;
    let mockGridSizeSelector: MemoizedSelector<fromGrid.State, GridSizeEnum>;
    let size: GridSizeEnum = GridSizeEnum.GRID_1


    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [
                HttpClientTestingModule,
                RouterTestingModule
            ],
            providers: [
                AgentService,
                provideMockStore({}),

            ],
        });

        agentService = TestBed.get(AgentService);
        mockStore = TestBed.get(Store);
        mockGridSizeSelector = mockStore.overrideSelector(fromGrid.getGridSize, size);
    });

    it('should return the default state', () => {

        const action = {} as GridActions;
        const state = fromGrid.reducer(fromGrid.initialState, action);
        expect(state).toBe(fromGrid.initialState);

    });

    it('should be created', () => {

        expect(agentService).toBeTruthy();
    });

    afterEach(() => {

    })


});

agent.service.ts :

the constructor part-

  constructor(private http: HttpClient,
    private router: Router,
    private store: Store<fromRoot.State>,
    private gridStore: Store<fromGrid.State>,
    private commandWebSocket: CommandWebsocketService,
    private logService: LogService) {

    this.commandWebSocket.connect();
    this.commandWebSocket.messages$.subscribe((data) => {
      this.commandWebsocketData(data);
    });

    this.store.pipe(select(fromGrid.getGridSize), takeUntil(this.destroyed$)).subscribe((size) => {
      if (size) {
        this.gridSize = size;
      }
    });

    this.gridStore.pipe(select(fromGrid.getGridVideoStreamIDs, this.gridSize), takeUntil(this.destroyed$)).subscribe(data => {
      if (data && data.length) {
        this.gridStreamIDs = data;
        const byPassCpuIdsCopy = this.byPassCpuIds;
        this.byPassCpuIds = [];
        this.gridStreamIDs.filter((dta) => {
          this.byPassCpuIds[dta] = byPassCpuIdsCopy[dta];
        });
      }
    });
  }

grid.reducer.ts :

export const getGridSize = createSelector(
  getGridFeatureState,
  state => state.size
);

This error appears a lot in another case, when I have subscribe to specific selector at constructor() or at ngOnInit() (if it component unit test ).

For solution i tried to initial the state in spec file, see above in agent.service.spec... but it isn't solved. Need your help, thanks!

How can i solve this error:

Cannot read properties of undefined (reading 'size')

Solution

  • You need to initialize your store:

    provideMockStore({
      grid: {     // assuming 'grid' is your feature key
        size: 5
      }
    })