Search code examples
angularunit-testingjasminekarma-runnerngrx

Override NGRX Store selector in test seems to get ingored


Overriding the selector whilst returning null still returns the data as returned by the override defined at initialization. Also tried setState but didnt work either.

Trying to test the else in this:

this.store.pipe(select(singleUserSelector, { _id: this.userModel?._id })).subscribe((state: IUserSelected) => {
  console.log('singleUserSelector', this.userModel?._id, state);
  if (state) {
    this.componentState = state.componentState;
    this.userModel = state.userModel;
    this.selected = true;
  } else if (this.selected) {
    this.componentState = ComponentState.VIEW;
    this.selected = false;
  }
});

Test

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
      imports: [ReactiveFormsModule],
      providers: [provideMockStore(
        {
          initialState,
          selectors: [
            { selector: usersSelector, value: users },
            { selector: singleUserSelector, value: { componentState: ComponentState.VIEW, userModel: userIndy } },
            { selector: mainComponentStateSelector, value: ComponentState.VIEW }]
        }
      )],
      declarations: [UserComponent],
    }).compileComponents();

    store = TestBed.inject(MockStore);

    fixture = TestBed.createComponent(UserComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should have not selected state based on singleUserSelector not returning valid user', () => {
    const mockedStateFocusedSelectorNull = store.overrideSelector(singleUserSelector, null);
    // setState doesnt work either
    // store.setState({ userFocused: null } as ApplicationState);
    fixture.detectChanges();

    expect(component.selected).toBeFalsy();
    expect(component.componentState).toBe(ComponentState.VIEW);
  });

Solution

  • This did the trick, obviously..

    const mockedStateFocusedSelectorNull = store.overrideSelector(singleUserSelector, null);
    store.refreshState(); // <------