rintoj/statex

How to mock store in components

Opened this issue ยท 5 comments

I've being looking around how to mock components in order to be tested, do you have an idea? https://github.com/rintoj/statex/blob/master/examples/todo-ng-ts/src/app/list/list.component.ts

Since you are doing a new instance of the store, it isn't quite easy to test it.

Thanks!

This is how I did it but I'm really not confortable with, if you have a better way please let us know :).

Love Statex man!!

Implementation:

private loadRooms(rooms: Room[], roomsNumber?: number) {
    if (!isUndefined(roomsNumber)) {
      if (roomsNumber > rooms.length) {
        this.dispatchedAction = new AddRoomsAction(roomsNumber);
      } else if (roomsNumber < rooms.length) {
        this.dispatchedAction = new RemoveRoomsAction(roomsNumber);
      }

      this.dispatchedAction.dispatch();
    }
  }

Unit test:

    it('should remove rooms', () => {
      const numberOfRoomsControl = {
        value: 0
      };

      component.rooms = [
        {
          id: '',
          name: '',
          ordinal: 3,
          isNew: true
        }
      ];

      component.onNumberOfRoomsChange(numberOfRoomsControl);
      expect(
        component.dispatchedAction instanceof RemoveRoomsAction
      ).toBeTruthy();
    });

@blopez2010, give me couple of hours. I will upload a test case for list component

@blopez2010, StateX is configured for detached store and view. Therefore when you unit test a view you must only test for appropriate actions being dispatched. What happens when an action is trigged must be tested under store's test case, not here.

This example should help you understand how to test that.

https://github.com/rintoj/statex/blob/master/examples/todo-ng-ts/src/app/list/list.component.spec.ts

Thanks @rintoj for the example!

frulo commented

I have some problems with the example above. What I forgot is to reset the state before each test:
initialize( {} )

an other possibility is the jasmin spy returns a correct state. example:
let toggleTodoActionCall = jasmine.createSpy('spy').and.returnValue(new ReplaceableState({}));