Search code examples
angularunit-testingkarma-jasminengrx-store

How to mock the store.pipe in a component in angular unit test


I am new to angular as i have tried to do unit test for one of the component which takes data from the store. I have mocked the service files as well as the store. When i try to run the test i am getting teh error like below. So i have added some fake data to the store and passed the datas.But still i am getting the same issue

Cannot read property 'switches' of undefined

Spec file

describe('SwitchListComponent', () => {
  let component: ListComponent;
  let fixture: ComponentFixture<ListComponent>;

  let store: Store<any>;
  const switchData = {
    switches: [
      {
        availability: true,
        created_at: "2020-01-30T05:06:06.366Z",
        description: "1",
        hardware_id: "2",
        id: 1018,
        max_flows: 2,
        name: "2",
        updated_at: "2020-01-30T05:34:36.702Z"
      }
    ],
    pagination: {
      currentPage: 1,
      endAt: 10,
      nextPage: 2,
      perPage: 10,
      prevPage: null,
      startAt: 1,
      totalCount: 1012,
      totalPages: 100
    }
  };


  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        ListComponent,
        MultiSelectComponent,
      ],
      imports: [
        RouterTestingModule,
        FormsModule,
        StoreModule.forRoot({ switchesReducer }),
      ],
      providers: [
        {provide: SwitchesService, useClass: SwitchesServiceStub},
      ]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ListComponent);
    component = fixture.componentInstance;
    store = fixture.debugElement.injector.get(Store);
    store.dispatch({
      type: 'FETCH_SWITCHES',
      payload: {
        switches: switchData.switches,
        pagination: switchData.pagination
      }
    });
    fixture.detectChanges();
  });

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

Switch List Component

this.store.pipe(select('switches')).subscribe(val => {
  this.rowData = val.switches;
  this.pagination = val.pagination;
  this.globalSearch = val.globalSearch;
});

can anyone tell me how to do the mocking for the this.store.pipe.


Solution

  • Inside the spec.ts try to change the below code from

    StoreModule.forRoot({ switchesReducer }),
    

    to

    StoreModule.forRoot({ switches: switchesReducer }),
    

    Pls refer the document for more info

    https://ngrx.io/guide/store/testing