0
votes

I am using NgRx Store in my angular application for state management.

In init function I am initializing data by selectors like below:

 ngOnInit() { 
  this.store.select(getData1).subscribe((result) => { 
     this.data1 = result; 
  });
  this.store.select(getData2).subscribe((result) => { 
     this.data2 = result; 
  });
}

In Test cases I have mocked store and checked like below:

 let storeMock = {
    select(): Observable<any> {
      return of([{key:'data1',value:'data1'}])
    }
}



beforeAll(async(() => {
    TestBed.configureTestingModule({
     providers:[{ provide: Store, useValue: storeMock }]
   });

Test case :

it('ngOnInit', () => {
    component.ngOnInit();
    expect(component.data1.key).toBe('data1');
    expect(component.data2.key).toBe('data2'); // in both cases it returns data1 as we have mocked only data 1
});

Problem here is I have mocked select method from Store but I couldn't return different value each time as I have called selector two times in ngOnInit but as I have mocked it with data it return same data for both selectors.

Is there any way , I can return different mock data for different time (by some parameters or sequence of calling selector like first time return different data second time return different data)

1

1 Answers

2
votes

Please consider using Testing utility from @ngrx/store/testing.

let mockStore: MockStore<MyState>;

beforeEach(() => {
  TestBed.configureTestingModule({
    providers: [
      provideMockStore(),
    ],
  });

  mockStore = TestBed.get(Store);
  mockStore.overrideSelector(getData1, {key:'data1',value:'data1'});
  mockStore.overrideSelector(getData2, {key:'data2',value:'data2'});
}