Angad
Angad

Reputation: 1174

Mock @ngrx/store in angular 2

I am using store in my application like below and it works fine.

export class NavigationComponent {
  navigationLinks$: Observable<Navigation[]>;

  constructor(private store: Store<State>) {
    this.navigationLinks$ = this.store.select('navigation')
                                .map((result: State) => result.navigationLinks);
   }

Now, I am trying to create a unit test and want to mock this store. This is what i am doing:

1. Creating the Mock Store Creating a mock store which will return mock data when this.store.select('') is called. The mockdata returns a property of array type called navigationLinks.

class StoreMock {
  public dispatch(obj) {
    console.log('dispatching from the mock store!')
  }

  public select(obj) {
    console.log('selecting from the mock store!');

    return Observable.of([
       { 'navigaitonLinks$': [{ 'name': 'Help', hasChild: false}] }
    ])
  }
}

2. BeforeEach blocks

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [NavigationComponent],
      providers: [{provide: Store, useClass: StoreMock}],
      imports: [
        StoreModule.provideStore(reducers)
      ],
    })
      .compileComponents();
  }));

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

3. My test I know this test will fail as per the expect statement but I am not able to populate the navigationLinks$ property with my mock data.

 it(`should create the navigation with 'Help' link`, () => {

    let navLinks: any[];
    component.navigationLinks$.subscribe();
    console.log(navLinks); // This should print my mockdata so i can assert it
    expect(component.navigationLinks$).toEqual('Help');
  });

The console.log prints undefined and is not able to read the data that MockStore select() is returning. Is there something extra I need to do?

Upvotes: 1

Views: 830

Answers (1)

GiXtarr Jo
GiXtarr Jo

Reputation: 11

I have the same issue, and I just return the object with Observable.of() function.

return Observable.of([
   { 'navigaitonLinks$': [{ 'name': 'Help', hasChild: false}] }
])

to

return Observable.of([{ 'name': 'Help', hasChild: false}, {}, {} ... ]);

This will populate your Observable object :

it(`should create the navigation with 'Help' link`, () => {
    component.navigationLinks$.subscribe((links) => {
    console.log(links); // This should print an array of Links
  });
});

Upvotes: 1

Related Questions