错误:已调用spy MovieService.getWatchListedMovies已被调用。角度单位测试

问题描述 投票:0回答:1
  • 一个名为watchlist的组件文件,它依赖于MovieService(服务)来获取电影。
  • 调用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对象对组件(监视列表)进行单元测试
  • 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 unit-testing jasmine karma-jasmine spy
1个回答
0
投票

只是一个猜测,尝试移动线

movieServiceFake = TestBed.get(MovieService);

进入测试的开始,就像

it('should call ngOnInIt', () => {
    movieServiceFake = TestBed.get(MovieService);
    ....
});
© www.soinside.com 2019 - 2024. All rights reserved.