ngrx / store

RxJS powered state management for Angular applications, inspired by Redux
MIT License
3.9k stars 310 forks source link

[Question] Testing Components with actions #428

Closed hemantjadon closed 7 years ago

hemantjadon commented 7 years ago

What is the neat way to test for the component to dispatch an Action, whenever some Action has taken place?

The context here is

@Component({
   selector: 'app-foo',
   template: '<button (click)="someFunction($event)">Click Me!</button>'
})
class AppComponent {
   constructor(
      private store: Store<RootState>
   ) {}
   someFunction() {
       this.store.dispatch(new ClickAction());
   }
}

So my question here is how to test gracefully that this component has a button which on click dispatches ClickAction

Zyzle commented 7 years ago

I'm not sure if this is best practice or not but generally if I want to test something like this in my spec file I have in beforeEach

TestBed.configureTestingModule({
  imports: [
    StoreModule.provideStore({})
  ],
  // .. any other items for test bed
})
// ...
store = TestBed.get(Store);

Then in my actual it functions:


const dispatchSpy = spyOn(store, 'dispatch').and.callThrough();
// click your button with triggerEventHandler
expect(dispatchSpy.calls.count()).toEqual(1);
expect(dispatchSpy.calls.mostRecent().args[0]).toEqual(/* your action */);
robwormald commented 7 years ago

Please check this against NgRx v4, and if it’s still an issue, please reopen on https://github.com/ngrx/platform. Thanks!