How to mock ofActionSuccessful from ngxs

Viewed 95

I have a component with ngOnInit that looks like

  ngOnInit() {
this.integrationsFacadeService.getTemplates();
this.actions$
  .pipe(ofActionSuccessful(GetTemplates))
  .subscribe(() => this.integrationsFacadeService.getTemplateOptions());
this.fields = this.getFields();
}

And then in my test module

describe('AdminCenterIntegrationAddComponent', () => {
  let component: AdminCenterIntegrationAddComponent;
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [AdminCenterIntegrationAddComponent, { provide: Actions, useValue: createSpyFromClass(Actions) }],
    }).compileComponents();
    component = TestBed.inject<any>(AdminCenterIntegrationAddComponent);
  });
  it('should be truthy', () => {
    expect(component).toBeTruthy();
  });

  it('ngOnInt should be ok', () => {
    component.ngOnInit();
  });
});

But the 'ngOnInt should be ok' fails at this line

this.actions$
  .pipe(ofActionSuccessful(GetTemplates))
  .subscribe(() => this.integrationsFacadeService.getTemplateOptions());

with the error:

TypeError: Cannot read property 'subscribe' of undefined

I have tried to mock ofActionSuccessful like:

        ofActionSuccessful: () => {
          return () => {
            return of([]);
          };
        }

but I still get the same error.

Any insights are appreciated.

1 Answers

You can use new Subject<ActionContext>();

beforeEach(async () => {
    store = spyStore();
    await TestBed.configureTestingModule({
      declarations: [
        YourComponent,
      ],
      providers: [
        { provide: Actions, useValue: actionsCtx },
      ],
    })
      .compileComponents();
  });

  it('...', () => {
    ...
    actionsCtx.next({
      status: ActionStatus.Successful,
      action: ProjectLoadAllJobs
    });
    // you might need a tick();
    ...
    excpect(...)...
  })
Related