I don't know if this that I want to do is possible, I have one component FiltersComponent
and one Service FiltersService
.
In FiltersService I have one attribute onFilterChange of type BehaviorSubject. I expose it asObservable and I want to test when I applied the change this observable is throw.
FilterService.service.ts
export class FilterService {
private _onFilterChange$: BehaviorSubject<any>;
constructor() {}
get onFilterChange(): any {
return this._onFilterChange$.asObservable;
}
public onApplyFilter(filter) {
this._onFilterChange$.next(filter);
}
}
FilterComponent
export class FiltersComponent implements OnInit, OnDestroy {
filterForm: FormGroup;
constructor(private _filterService: FilterService){}
onApplyFilter() {
const pfilter = this.filterForm.getRawValue();
this._filterService.onApplyFilter(newF);
}
}
How can I test when I apply a filter
this._filterService.onApplyFilter(newF);
this._filterService.onFilterChange().subscribe(d => {
respond the same filter that I apllied
});
From your question's tags, I could see that you are using jasmine-marbles
to test the observables. If so then you should set up your FilterService
like this:
export class FilterService {
private _onFilterChange$: BehaviorSubject<any> = new BehaviorSubject<any>(null);
constructor() {}
get onFilterChange(): Observable<any> {
return this._onFilterChange$.asObservable();
}
public onApplyFilter(filter) {
this._onFilterChange$.next(filter);
}
}
To Unit test, FilterService
, have the following code in filter.service.spec.ts
file:
import { TestBed } from '@angular/core/testing';
import {cold} from 'jasmine-marbles';
import { FilterService } from './filter.service';
describe('FilterService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: FilterService = TestBed.get(FilterService);
const expected = cold('a', {a: 2});
service.onApplyFilter(2);
const p = service.onFilterChange;
expect(p).toBeObservable(expected);
});
});