axel
axel

Reputation: 4127

How to test ngrx/effects with Jasmine / Karma with Angular5, ngrx5?

this is the file I need to test. I'm working with Angular5 (^5.2.0), ngrx5 (^5.2.0) and currently my attention is on some effects service. This is my current code that needs to be tested. But I've no idea how to implement it properly, I did some attempts but they were just failures. Do you guys have anby tips? Thanks

import { Injectable } from '@angular/core';
import { Actions, Effect } from '@ngrx/effects';
import { FETCH_DATA } from '../reducers/data.reducer';
import { DataService } from './data.service';
import { Subject } from 'rxjs/Subject';
import { ActionWithPayload } from '../types/app-actions';

@Injectable()
export class AutoCompleteEffects {
  public autoComplete$ = new Subject<{
    type: string;
    payload: { results: string[]; searchValue: string };
  }>();

  @Effect()
  getData$ = this.actions$.ofType(FETCH_DATA).switchMap((action: ActionWithPayload) => {
    return this.data
      .getData(action.payload)
      .map(results => ({
    type: 'FETCHED_DATA',
    payload: { results, searchValue: action.payload }
      }))
      .catch(() =>
    Observable.of({
      type: 'FETCHED_DATA',
      payload: { results: [], searchValue: action.payload }
    })
      );
  });


  constructor(
    private actions$: Actions,
    private data: DataService,
  ) {
    this.getData$.subscribe(action => this.autoComplete$.next(action));
  }

  public getAutoCompleteEffects() {
    return this.autoComplete$.asObservable();
  }
}

Upvotes: 1

Views: 853

Answers (1)

Pramodh Valavala
Pramodh Valavala

Reputation: 752

There are a couple of things that you need to have

  1. Follow the ngrx effects testing setup with provideMockActions (Refer this)
  2. Mock the DataService and inject that

After that, it's just a test with different actions

it('should suggest auto complete values', () => {
  actions = of([<test-actions>]);
  const expectedEffects = of([<expected-actions-from-effects>]);

  expect(TestBed.get(AutoCompleteEffects).getData$).toBeObservable(expectedEffects);
});

Upvotes: 1

Related Questions