I'm mocking an injected angular service to test one of my components. However, the component always receives an empty array when subscribing to an observable from the mock service.
Segment from movies.service.mock
:
export class MoviesServiceMock {
private readonly _movies = new BehaviorSubject<Array<MovieFull>>([]);
readonly movies$ = this._movies.asObservable();
getMovies = (): void => {
this._movies.next(this.sortByTitle(mockMovieData));
console.log(this._movies.getValue()[0]); // this shows the expected value
};
// ...
}
Segment from movie-details-page.component.ts
:
getMovieDetails = (imdbID: string) => {
this.moviesService.movies$.subscribe(movies => {
console.log(movies); // this always shows []
if (!movies || !movies.length) return;
const movie = movies.find(m => m.imdb_id === imdbID);
if (movie) this.setMovie(movie);
else this.moviesService.getMovieDetails(imdbID).subscribe(this.setMovie);
});
};
Segment from movie-details-page.component.spec.ts
:
describe('MovieDetailsPageComponent', () => {
// ...
beforeEach(done => {
fixture = TestBed.createComponent(MovieDetailsPageComponent);
component = fixture.componentInstance;
fixture.detectChanges();
debugElement = fixture.debugElement;
// grab movies service and initialize it with our mock movie data
const moviesService = debugElement.injector.get(MoviesServiceMock);
moviesService.getMovies();
// force inject the movie using the mock service
moviesService.movies$.subscribe(movies => {
//movie = movies[0];
//component.setMovie(movie); // forcefully setting the movie here works, but defeats the purpose of the test
fixture.detectChanges();
done();
});
});
// ...
});
I'm really puzzled here as I can see in my debug console logs that the data is there in the mock service, but for some reason the subscribe() method called in the component appears to be broken when running tests.
Aucun commentaire:
Enregistrer un commentaire