【发布时间】:2016-06-19 01:12:54
【问题描述】:
只是在搞乱moviedb api,并试图为我的navigationGenre 函数编写一个测试,但我不断收到错误:
TypeError: 无法读取未定义的属性“id”
这是规范和控制器代码:
规格:
describe('Genre List Controller', function(){
var ctrl, scope;
beforeEach(module('MovieFinder'));
beforeEach(inject(function($controller, $route, $rootScope, _$location_, _GenreListFactory_){
scope = $rootScope.$new();
var $location = _$location_;
var GenreListFactory = _GenreListFactory_;
$route.current = {
params: {
genreId: 18
}
};
ctrl = $controller('GenreListCtrl', {
$scope: scope,
$location: $location,
GenreListFactory: GenreListFactory,
$route: $route
});
}));
fit('should route to correct genre when navigateGenre() is called',
inject(function($httpBackend, $rootScope, $route, $location){
$httpBackend.expect('JSONP', 'http://api.themoviedb.org/3/genre/movie/list?api_key=&callback=JSON_CALLBACK').respond(200);
$httpBackend.expect('GET', 'js/genre-detail/genre-detail.html').respond(200);
$rootScope.$apply(function(){
$location.path('/genre/18');
});
$rootScope.$apply(function(){
scope.navigateGenre();
});
expect($route.current.originalPath).toBe('/genre/:genreId');
expect($route.current.params.genreId).toBe();
}));
});
控制器:
MovieFinder
.controller('GenreListCtrl', ['$scope', '$route', '$location', 'GenreListFactory', function($scope, $route, $location, GenreListFactory){
GenreListFactory().then(function(genres){
console.log('GenreListCtrl', genres);
$scope.test = 'test';
$scope.genreList = [{id: null, name: 'Select a Genre'}];
genres.data.genres.forEach(function(genre){
//console.log(genre.name);
$scope.genreList.push(genre);
});
$scope.selectedGenre = $scope.genreList[0];
});
$scope.navigateGenre = function(){
if($scope.selectedGenre.id !== null){
$location.path('genre/' + $scope.selectedGenre.id);
$scope.selectedGenre = $scope.genreList[0];
}
};
}]);
任何帮助将不胜感激。 如果我需要包含任何内容,请告诉我。
【问题讨论】:
-
据我所知。您应该首先尝试使用一些模拟数据来解决承诺,然后只有您的 $scope.genreList 和 $scope.selectedGenre 将被初始化。您正在调用 navigationGenre 函数,但 $scope.selectedGenre 没有在任何地方初始化。
-
@Diljohn5741 感谢您的建议,我会尝试一下,看看是否可以让它工作