2016-07-13 7 views
1

Я тестирую устройство с кармой/жасмином, и у меня возникают ошибки с модулем тестирования моего контроллера. контроллер код:Смещение переменной в модульных тестах

angular.module('app.controllers', []) 
    .controller('myctrl1',[function($scope){ 
     $scope.test = "this worked"; 
    }]) 

Unit Test Code:

describe('Controllers', function(){ //describe your object type 
    beforeEach(module('app.controllers')); //load module<br /> 
    describe('Running Test for :',function(){ //describe your app name<br /> 
     var myctrl; 
     beforeEach(inject(function($controller){ //instantiate controller using $controller service 
      myctrl = $controller('myctrl1'); 
     })); 
     it('Test scope var', function(){ //write tests 
      expect($scope.test).toBe('this worked'); //pass 
     }); 
    }); 
}); 

Я получаю следующее сообщение об ошибке:

TypeError: Cannot set property 'test' of undefined 
ReferenceError: $scope is not defined 

ответ

2

Изменить ваш тест на:

angular.module('app.controllers', ['ngMockE2E']) 
 

 
.controller('myCtrl1', function($scope) { 
 
    $scope.test = "this worked"; 
 
}); 
 

 
describe('Main Controller test suite', function() { 
 

 
    describe('myCtrl1', function() { 
 
    var $scope; 
 

 
    beforeEach(module('app.controllers')); 
 

 
    beforeEach(inject(function($rootScope, $controller) { 
 
     $scope = $rootScope.$new(); 
 
     $controller('myCtrl1', { 
 
     $scope: $scope 
 
     }); 
 
    })); 
 

 
    it('Test scope var', function() { 
 
     expect($scope.test).toBe('this worked'); //pass 
 
    }); 
 
    }); 
 
});
<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine.min.css" /> 
 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine.min.js"></script> 
 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine-html.js"></script> 
 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/boot.min.js"></script> 
 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script> 
 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular-mocks.js"></script> 
 
</head> 
 

 
<body> 
 
    <h1>Angular controller test with Jasmine</h1> 
 
</body> 
 

 
</html>

Ссылка:https://docs.angularjs.org/guide/unit-testing#testing-a-controller

+0

TypeError: Невозможно установить свойство 'тест' неопределенной ReferenceError: $ контроллера не определен – user1650487

+0

ту же ошибку, как и раньше – user1650487

+0

@ user1650487, это работает? – developer033

Смежные вопросы