I am currently testing an observable feature from a service in Angular. This particular observable will output a boolean value based on the queryParam provided.
For effective testing of this observable, it is essential to mock the queryParam value.
However, the expectations set up in the test file are returning false for both scenarios because no queryParam value is being received.
Below is the content of the service file:
import { Injectable } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { BehaviorSubject, Observable } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class BirdService {
private readonly _bird$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(this.birdStatus);
constructor(private route: ActivatedRoute) {}
public get bird$(): Observable<boolean> {
return this._bird$.asObservable();
}
private get birdStatus(): boolean {
const isBird = this.route.snapshot.queryParamMap.get('bird') === 'true';
if (isBird) return true;
return false;
}
}
And here is the corresponding test file:
import { TestBed } from '@angular/core/testing';
import { ActivatedRouteSnapshot } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { BirdService } from './birdService.service';
describe('BirdService', () => {
let service: BirdService;
let route: ActivatedRouteSnapshot;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule],
providers: [BirdService],
});
route = new ActivatedRouteSnapshot();
});
describe('When there is a bird present', () => {
it('should activate flying mode', (done) => {
route.queryParams = {
bird: 'true',
};
service = TestBed.inject(BirdService);
service.bird$.subscribe((value: boolean) => {
expect(value).toBe(true);
done();
});
});
});
describe('When there is NO bird around', () => {
it('should NOT activate flying mode', (done) => {
route.queryParams = {
bird: 'false',
};
service = TestBed.inject(BirdService);
service.bird$.subscribe((value: boolean) => {
expect(value).toBe(false);
done();
});
});
});
});