NGRX 8:测试发送动作的效果

时间:2019-10-15 09:07:32

标签: angular unit-testing jasmine ngrx

我想测试一个效果是否派遣了一个动作。逻辑上,下面的测试输出一个错误,告诉我createActionSuccess不是间谍 问题是我不知道我可以spyOn 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操作:

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

createOperation效果:

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 })));
      })
    )
);

谢谢。

1 个答案:

答案 0 :(得分:1)

// 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