Swapnil Mhaske
Swapnil Mhaske

Reputation: 365

ngrx component unit test : how to set store value and make the subscribe call

I am writing a unit test for my component. I want to test/cover the part wherein I am calling a function calculateJohnDoe inside my subscribe. Please refer below :

ngOnInit(): void {
    this.authStore$ = this.store.select('auth');
    this.authStore$.subscribe(authData => {
      if (authData && authData.myprop) {
          this.calculateJohnDoe();
        }
    });
}

What I am trying to do in my spec is as follows :

describe(..., () => {
  let mockStore: MockStore<AuthState>;

    // Testbed configuration
      providers: [ Store ]
      }).compileComponents();

      mockStore = TestBed.get(Store);
    ...

    it('should call the function', () => {
        mockStore.setState({
           myprop: true
        });
        const spy = jest.spyOn(LoginComponent.prototype, 'calculateJohnDoe');
        expect(spy).toHaveBeenCalled();
    });

    ...

});

But the problem is I never get the myprop true updated store event/callack in my component ts file called.

Upvotes: 0

Views: 1123

Answers (1)

Julien METRAL
Julien METRAL

Reputation: 1974

You can create a mock service that represents your store, this class will simulate an observable subject with the attribute _anObservable :

class MockService {
    _anObservable = new Subject();
    select(prop: string) {
        return this._anObservable.asObservable();
    }
}

describe(..., () => {

    // Testbed configuration
    providers: [
        { provide: YourStore, useClass: MockService }
    ]

    ...

    it('should call the function', inject([YourStore], (store) => {
        const spy = jest.spyOn(LoginComponent.prototype, 'calculateJohnDoe');
        store._anObservable.next({
            myprop: true
        });
        expect(spy).toHaveBeenCalled();
    }));

    ...

});

Upvotes: 1

Related Questions