statex icon indicating copy to clipboard operation
statex copied to clipboard

How to mock store in components

Open blopez2010 opened this issue 7 years ago • 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!

blopez2010 avatar Feb 12 '18 17:02 blopez2010

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 avatar Feb 12 '18 17:02 blopez2010

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

rintoj avatar Feb 12 '18 17:02 rintoj

@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

rintoj avatar Feb 12 '18 19:02 rintoj

Thanks @rintoj for the example!

blopez2010 avatar Feb 12 '18 20:02 blopez2010

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

frulo avatar Aug 30 '18 13:08 frulo