麻烦 运行 angular 测试中的范围函数
Trouble running a scope function in angular test
我最近开始尝试学习如何测试 angular。我取得了一些成功,但目前我正在尝试测试一个指令,但我似乎无法让它发挥作用。
测试码
describe('navigation test', function(){
var element, location, route, rootScope, scope, httpBackend;
var elm;
beforeEach(module('myApp'));
beforeEach(inject(function($compile,$rootScope,$location,$httpBackend,$route) {
location = $location;
scope = $rootScope.$new();
route = $route;
$httpBackend.whenGET('partials/nav/nav.html')
.respond(200);
element = $compile("<navigation></navigation>")(scope);
httpBackend = $httpBackend;
scope.$digest();
}));
describe('Change page function',function(){
it('should flip the location between /home and /test', function(){
location.path('/home')
scope.changePage();
scope.$digest();
expect(location.path()).to.equal('/test');
})
})
});
指令函数
var app = angular.module('myApp');
app.directive('navigation', function($location, $q, $sce, $timeout, $mdSidenav, $mdComponentRegistry) {
return {
restrict: 'E',
templateUrl: 'partials/nav/nav.html',
link: function(scope, elements, attrs) {
scope.changePage = function() {
if($location.path() == '/home') {
$location.path('/builder')
} else {
$location.path('/home');
}
};
});
我收到的错误是
错误信息
TypeError: 'undefined' is not a function
(正在评估 'scope.changePage()')
我不明白为什么它看不到范围。任何帮助将不胜感激。如果有人可以阐明 angular 测试,那就太好了。
您在构造 directive
时忘记调用 $httpBackend.flush()
来为对 partials/nav/nav.html
的请求提供服务。只需添加它,它应该可以正常工作。
我最近开始尝试学习如何测试 angular。我取得了一些成功,但目前我正在尝试测试一个指令,但我似乎无法让它发挥作用。
测试码
describe('navigation test', function(){
var element, location, route, rootScope, scope, httpBackend;
var elm;
beforeEach(module('myApp'));
beforeEach(inject(function($compile,$rootScope,$location,$httpBackend,$route) {
location = $location;
scope = $rootScope.$new();
route = $route;
$httpBackend.whenGET('partials/nav/nav.html')
.respond(200);
element = $compile("<navigation></navigation>")(scope);
httpBackend = $httpBackend;
scope.$digest();
}));
describe('Change page function',function(){
it('should flip the location between /home and /test', function(){
location.path('/home')
scope.changePage();
scope.$digest();
expect(location.path()).to.equal('/test');
})
})
});
指令函数
var app = angular.module('myApp');
app.directive('navigation', function($location, $q, $sce, $timeout, $mdSidenav, $mdComponentRegistry) {
return {
restrict: 'E',
templateUrl: 'partials/nav/nav.html',
link: function(scope, elements, attrs) {
scope.changePage = function() {
if($location.path() == '/home') {
$location.path('/builder')
} else {
$location.path('/home');
}
};
}); 我收到的错误是
错误信息
TypeError: 'undefined' is not a function
(正在评估 'scope.changePage()')
我不明白为什么它看不到范围。任何帮助将不胜感激。如果有人可以阐明 angular 测试,那就太好了。
您在构造 directive
时忘记调用 $httpBackend.flush()
来为对 partials/nav/nav.html
的请求提供服务。只需添加它,它应该可以正常工作。