export class WatchlistComponent implements OnInit {
movies: Array<Movie>;
movieType:string;
constructor(private movieService:MovieService,private route:ActivatedRoute) {
this.movies=[];
this.route.data.subscribe((data)=>{
this.movieType=data.movieType
});
}
ngOnInit() {
this.movieService.getWatchListedMovies()
.subscribe((movies)=>{
this.movies.push(...movies);
},
this.handleErrors()
);
}
describe('WatchlistComponent', () => {
let component: WatchlistComponent;
let fixture: ComponentFixture<WatchlistComponent>;
let movieServiceFake:jasmine.SpyObj<MovieService>;
let movieService;
let stubTmdbMovies: Movie[];
beforeEach(async(() => {
movieServiceFake = jasmine.createSpyObj('MovieService', ['getWatchListedMovies']);
TestBed.configureTestingModule({
imports: [MovieModule,
RouterTestingModule,
HttpClientTestingModule],
providers: [{ provide: MovieService, useValue: movieServiceFake }]
})
}));
beforeEach(() => {
fixture = TestBed.createComponent(WatchlistComponent);
component = fixture.componentInstance;
movieServiceFake = TestBed.get(MovieService);
});
it('should create watchlist', () => {
expect(component).toBeTruthy();
});
it('should call ngOnInIt', () => {
//Arrange
let spyOnComponent = spyOn(component, 'ngOnInit');
movieServiceFake.getWatchListedMovies.and.callFake(() => { return of(stubTmdbMovies) });
//Act
component.ngOnInit();
//Assert
expect(spyOnComponent).toHaveBeenCalled();
expect(movieServiceFake.getWatchListedMovies).toHaveBeenCalled();//error line
});
});
`MovieModule我在哪里注册了watchlist和MovieService。如下
@NgModule({
imports: [
CommonModule,
HttpClientModule,
MovieRouterModule,
MatCardModule,
MatButtonModule,
MatSnackBarModule,
FormsModule,
ReactiveFormsModule,
MatInputModule
],
declarations: [ContainerComponent,TmdbContainerComponent,TumbnailComponent, WatchlistComponent, MovieDetailsComponent],
exports:[
MovieRouterModule,
TumbnailComponent,
ContainerComponent,
TmdbContainerComponent
],
providers:[
MovieService
]
})
export class MovieModule { }
只是一个猜测,尝试移动线
movieServiceFake = TestBed.get(MovieService);
进入测试的开始,就像
it('should call ngOnInIt', () => {
movieServiceFake = TestBed.get(MovieService);
....
});