I'm relatively new to Angular and I'm currently experimenting with testing the implementation of a component that relies on a RecipesServices
service containing a BehaviorSubject
named selectedRecipe
:
@Component({
selector: 'app-recipe',
templateUrl: './recipe.page.html',
styleUrls: ['./recipe.page.scss'],
})
export class RecipePage implements OnInit {
selectedRecipe: Recipe;
constructor(
private recipesService: RecipesService
) {
this.recipesService.selectedRecipe.subscribe(newRecipe => this.selectedRecipe = newRecipe);
}
}
Below is the structure of the service:
@Injectable({
providedIn: 'root'
})
export class RecipesService {
/**
* Representing the recipe selected by the user
*/
readonly selectedRecipe : BehaviorSubject<Recipe> = new BehaviorSubject(null);
constructor(
private httpClient: HttpClient
) {}
...
}
I've been attempting various methods to mock this service and include it as a provider in the component's test, but I seem to be running out of ideas. The current test I'm working on yields an error stating "Failed: this.recipesService.selectedRecipe.subscribe is not a function":
import { HttpClient } from '@angular/common/http';
import { ComponentFixture, fakeAsync, TestBed, waitForAsync } from '@angular/core/testing';
import { Router, UrlSerializer } from '@angular/router';
import { IonicModule } from '@ionic/angular';
import { BehaviorSubject, defer, Observable, of, Subject } from 'rxjs';
import { Recipe } from '../recipes-list/recipe';
import { RecipesService } from '../recipes-list/services/recipes.service';
import { RecipePage } from './recipe.page';
let mockrecipesService = {
selectedRecipe: BehaviorSubject
}
describe('RecipePage', () => {
let component: RecipePage;
let fixture: ComponentFixture<RecipePage>;
var httpClientStub: HttpClient;
let urlSerializerStub = {};
let routerStub = {};
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [ RecipePage ],
imports: [IonicModule.forRoot()],
providers: [
{ provide: HttpClient, useValue: httpClientStub },
{ provide: UrlSerializer, useValue: urlSerializerStub },
{ provide: Router, useValue: routerStub },
{ provide: RecipesService, useValue: mockrecipesService}
]
}).compileComponents();
spyOn(mockrecipesService, 'selectedRecipe').and.returnValue(new BehaviorSubject<Recipe>(null));
fixture = TestBed.createComponent(RecipePage);
component = fixture.componentInstance;
fixture.detectChanges();
}));
it('should create', () => {
expect(component).toBeTruthy();
});
});
Your assistance is greatly appreciated!