【发布时间】:2019-03-01 13:13:55
【问题描述】:
一个名为 watchlist 的组件文件,它依赖于 MovieService(service) 来获取电影。
调用 ngOnInit() 将调用 MovieService.getWatchlistedMovies()
组件代码如下,
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()
);
}
-
使用 movieService(Service) 上的 jasmine.spy 对象对 component(watchlist) 进行单元测试
watchlist.spec.ts文件代码如下,
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 { }
【问题讨论】:
-
大家好,请查看。
-
你好阿伦,你能在一些句子上加点字符,这样你的问题就更易读了。避免使用长句。还要解释上下文、语言并提供更多信息。提供一些作为 Angular 或单元测试的键是好的,但还不够。我已经把你的问题读了 3 遍,我认为它可以改进。
-
尝试将
getWatchListedMovies.and.callFake(() => { return of(stubTmdbMovies) });替换为getWatchListedMovies.and.callFake(() => console.log("I have been called"));并检查是否将消息打印到控制台 -
@schlebe 感谢您的反馈。我会更新我的问题。
-
@AmirArbabian 我试过了,只有空的控制台日志。还有其他解决办法吗?
标签: angular unit-testing jasmine karma-jasmine spy