如何对这种效果进行单元测试(使用{dispatch:false})?

cam*_*kid 10 unit-testing ngrx-effects angular

ngrx和单元测试初学者在这里.我有以下效果:

@Injectable()
export class NotificationEffects {
  @Effect({dispatch: false})
  notificationShow$ = this.actions$
    .ofType(notificationAction.NOTIFICATION_SHOW)
    .do((action: notificationAction.NotificationShowAction) => {
      this.notificationService.info(action.payload.config);
    });

  constructor(private actions$: Actions, private notificationService: NotificationService) {}
}
Run Code Online (Sandbox Code Playgroud)

具体来说,我想测试一下是否调用了notificationService方法信息.我该怎么办?

我已经按照这些示例但没有找到解决方案:

https://netbasal.com/unit-test-your-ngrx-effects-in-angular-1bf2142dd459 https://medium.com/@adrianfaciu/testing-ngrx-effects-3682cb5d760e https://github.com/ngrx /effects/blob/master/docs/testing.md

cam*_*kid 16

所以它就像这样简单:

describe('notificationShow$', () => {
  let effects: NotificationEffects;
  let service: any;
  let actions$: Observable<Action>;
  const payload = {test: 123};

  beforeEach( () => {
    TestBed.configureTestingModule( {
      providers: [
        NotificationEffects,
        provideMockActions( () => actions$ ),
        {
          provide: NotificationService,
          useValue: jasmine.createSpyObj('NotificationService', ['info'])
        }
      ]
    } );

    effects = TestBed.get(NotificationEffects);
    service = TestBed.get(NotificationService);
  });

  it('should call a notification service method info with a payload', () => {
    actions$ = cold('a', { a: new notificationAction.NotificationShowAction(payload) });
    effects.notificationShow$.subscribe(() => {
      expect(service.info).toHaveBeenCalledWith(payload);
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

  • 我有完全相同的设置,由于某种原因,subscribe块中的代码永远不会被调用。我什至在其中放入了“ expect(true).toEqual(false);”,它永远不会失败。使用ngrx ^ 7.0.0 (2认同)
  • 我同意楼上说的,这个不行!什么有效是上面评论中的问题。您必须以某种方式使用异步,否则测试如何知道它需要等待订阅! (2认同)

Tra*_*oud 5

最简单(官方建议)的方法是这样做:

    it('should navigate to the customers detail page', () => {
      actions$ = of({ type: '[Customers Page] Customer Selected', name: 'Bob' });

      // create a spy to verify the navigation will be called
      spyOn(router, 'navigateByUrl');

      // subscribe to execute the Effect
      effects.selectCustomer$.subscribe();

      // verify the navigation has been called
      expect(router.navigateByUrl).toHaveBeenCalledWith('customers/bob');
    });
Run Code Online (Sandbox Code Playgroud)

这是来源