Reputation: 552
I have recently started trying to learn how to test angular. I have had some success but at the moment I am trying to test a directive and I cannot seem to make it work.
Test code
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');
})
})
});
Directive function
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');
}
};
}); The error I am receiving is
error message
TypeError: 'undefined' is not a function
(evaluating 'scope.changePage()')
I cannot figure out why it cannot see the scope. Any help would be greatly appreciated. And if anyone could shed some light on angular testing that would be great.
Upvotes: 0
Views: 81
Reputation: 1738
You forgot to call $httpBackend.flush()
to serve the request to partials/nav/nav.html
when you construct the directive
. Just add it in and it should be working fine.
Upvotes: 1