Search code examples
angularunit-testingjasminengrx

NGRX 8: Test an effect that dispatches an action


I would like to test that an effect dispatches an action. Logically, The test below outputs an error telling me that createActionSuccess isn't a spy The problem is that I don't know I could spyOn the createOperationSuccess.

describe('[OPERATION] Create Operation', () => {
    it(' should trigger createoperation from operation service', (done) => {
      actions$ = of({type: createOperation.type, operation: CreateOperationDTOMock});
      spyOn(service, 'create').and.callThrough();
      effects.createOperation$.subscribe(t => {
        expect(service.create).toHaveBeenCalledWith(CreateOperationDTOMock);
        expect(createOperationSuccess).toHaveBeenCalledWith({operation_id: OperationMock._id});
        done();
      });
    });
 });

createOperationSuccess Action:

export const createOperationSuccess = createAction(
  '[OPERATION] Create Operation Success',
  props<{ operation_id: string }>()
);

createOperation effect:

createOperation$ = createEffect(() =>
    this.actions$.pipe(
      ofType(createOperation),
      concatMap(payload => {
        return this.operationService
          .create(payload.operation)
          // I want to test that line below saying that createOperationSuccess has been triggered.
          .pipe(map(operation_id => createOperationSuccess({ operation_id })));
      })
    )
);

Thanks in advance.


Solution

  • // create an actions stream and immediately dispatch a GET action
    actions$ = of({ type: 'GET CUSTOMERS' });
    
    // mock the service to prevent an HTTP request
    customersServiceSpy.getAllCustomers.and.returnValue(of([...]));
    
    // subscribe to the Effect stream and verify it dispatches a SUCCESS action
    effects.getAll$.subscribe(action => {
      expect(action).toEqual({
        type: 'GET CUSTOMERS SUCCESS',
        customers: [...],
      });
    });
    

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