Angular 2+测试组件

时间:2018-08-15 19:28:20

标签: javascript angular unit-testing jasmine angular6

我有以下服务可调用API:

export class MoviesService {

    constructor(private httpClient: HttpClient) { }

    // Return an obsevable with all the movies from the API
    getAllMovies(): Observable<Movie[]> {
        return this.httpClient.get<EmbeddedTitle>("http://localhost:8080/api/movies", { params: params })
        .pipe(
            map(response => {
                return response;
            }
            ));
}

以下是注入该服务并调用 getAllMovies 方法的组件:

export class MoviesListingComponent implements OnInit {

    public movies: Movie[];

    constructor(private moviesService: MoviesService) { }

    ngOnInit(): void {
        this.getAllMovies();
    }

    // Subscribe to method service (getAllMovies) and assign the results to a class object (movies)
    getAllMovies(): void {
        this.moviesService.getAllMovies()
            .subscribe(movies => {
                this.movies = movies;
            });
    }

}

我想知道如何使用Jasmine对单元的方法 getAllMovies 进行单元测试。

1 个答案:

答案 0 :(得分:0)

方法getAllMovies()更改“ movies”变量的值,并且您的组件对保存数据的服务具有依赖关系,您的工作将模拟该服务并创建一个getAllMovies,以返回虚拟数据并确保您的电影字段包含您模拟的数据