angulartestingjestjsngrxngrx-effects

Jest create mock of property that reads from the store angular


I'm using Angular, NgRx and Jest.

I'm having the service which is reading from the store

export class MyFacade {
  configuration$ = this.store.select(selectors.selectConfiguration);
}

I'm using it in my spec file in which I'm testing the effects. I have created the mock class that is implementing it like this

export class MyMockFacade {
  configuration$ = of(configObject);
}

and my spec file looks likt this:


describe('Config Effects', () => {
  const mockStore = new MockStore();
    ....
  const mockFacade  = new MyMockFacade();

  let actions;
  let effects: ConfigEffects;

  beforeAll(() => {
    Object.defineProperty(window, 'location', {
      configurable: true,
      value: { reload: jest.fn() }
    });
  });
  beforeEach(() => {
    TestBed.configureTestingModule({
     
      providers: [
        ConfigEffects,
        HttpClientModule,
        provideMockActions(() => actions),
        { provide: Store, useValue: mockStore },
        ...
        { provide: MyFacade , useValue: mockFacade  },
      ]
    });
    effects = TestBed.inject(ConfigEffects);
  });
});

I'd like to have the possibility to change the value returned from the configuration$ in the test. How can I achieve it

 it('should call ....', () => {
    
    //I would like to be able to assigned new value here!

    
      expect(effects.loadXXX$).toSatisfyOnFlush(() => {
        ...
      });
    });

Solution

  • Make configuration$ a BehaviorSubject so you can specify the value it should emit:

    export class MyMockFacade {
      configuration$ = new BehaviorSubject<ConfigObject>(null);
    }
    
    it('should call ....', () => {
        mockFacade.configuration$.next(someConfigObject); 
    
        expect(effects.loadXXX$).toSatisfyOnFlush(() => {
          ...
        });
    });