Skip to content

Instantly share code, notes, and snippets.

@ottodranik
Last active April 28, 2023 20:16
Show Gist options
  • Save ottodranik/a39b691c007eb8ff625b7e844e3a051b to your computer and use it in GitHub Desktop.
Save ottodranik/a39b691c007eb8ff625b7e844e3a051b to your computer and use it in GitHub Desktop.
Test Subscription on ngrx selector inside component constructor
@Injectable()
export class SomeMenuService {
buildMobileMainMenu(descData: DataForMenuDescriptions) {
return { menu: 'menu' };
}
}
@Injectable()
export class SomeStoreService {
mobileMenuDescriptions$: Observable<DataForMenuDescriptions> = this._store.select(selectMobileMenuDescriptions);
constructor(private _store: Store<AppState>) { }
}
import { ActionsSubject } from '@ngrx/store';
const mockData = { somedata: 'somedata' };
const storeServiceStub = {
mobileMenuDescriptions$: new Subject(),
} as unknown as DashboardStoreService;
const menuMapServiceStub = {
buildMobileMainMenu: jest.fn().mockImplementation((data) => ({ data })),
} as unknown as MenuMapService;
const actionsSubjectMock = new ActionsSubject();
describe('SomeService', () => {
const service = new SomeService(
storeServiceStub,
menuServiceStub,
actionsSubjectMock,
);
describe('init', () => {
it('should return properly value on mobileMenuDescSubs$ subscribe', () => {
const spyMobileMenuNext = jest.spyOn(service.mobileMenu$, 'next');
(service.store.mobileMenuDescriptions$ as unknown as Subject<DataForMenuDescriptions>).next(mockData as unknown as DataForMenuDescriptions);
expect(menuServiceStub.buildMobileMainMenu).toHaveBeenCalledWith(mockData);
expect(spyMobileMenuNext).toHaveBeenCalledWith({ data: mockData });
});
it('should return properly value on actionsSubject$ subscribe', () => {
expect(service.isExternalNavigation).toEqual(false);
const action = { type: 'GoSomePage' };
actionsSubjectMock.next(action);
expect(service.isExternalNavigation).toEqual(true);
});
});
});
@Injectable()
export class SomeService {
private _mobileMenuDescSubs$: Subscription;
private _mobileMenu$ = new BehaviorSubject<MenuItem[]>([]);
private _isExternalNavigation = false;
constructor(
private _store: SomeStoreService,
private _menuService: SomeMenuService,
public _actionsSubject$: ActionsSubject,
) {
// TRY TO TEST THIS
this._mobileMenuDescSubs$ = this._store.mobileMenuDescriptions$.subscribe((dataForDescriptions: DataForMenuDescriptions) => {
this._mobileMenu$.next(this.buildMobileMenu(dataForDescriptions));
});
// AND TRY TO TEST THIS
this._actionsSubject$.subscribe(({ type }) => {
if (type === 'GoSomePage') {
this.isExternalNavigation = true;
}
});
}
set isExternalNavigation(value) {
this._isExternalNavigation = value;
}
get isExternalNavigation() {
return this._isExternalNavigation;
}
private buildMobileMenu(dataForDescriptions: DataForMenuDescriptions) {
return this._menuService.buildMobileMenu(dataForDescriptions);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment