这里是测试规范文件:
describe('Test main controller',function(){ it('Should initialize value to Loading',function(){ $scope = {} ctrl = new mainNavController($scope) expect($scope.wksp_name).toBe('Loading') }) })
这里是控制器文件
function mainNavController($scope) { $scope.wksp_name = 'Loading...' $scope.$on('broadCastWkspNameEvent',function (e,args) { $scope.wksp_name = args }) } mainNavController.$inject=['$scope']
但我的测试失败说Object#< Object>没有方法“$ on”
我使用茉莉花的基本设置。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Jasmine Spec Runner</title> <link rel="shortcut icon" type="image/png" href="testlib/jasmine-1.2.0/jasmine_favicon.png"> <link rel="stylesheet" type="text/css" href="testlib/jasmine-1.2.0/jasmine.css"> <script type="text/javascript" src="testlib/jasmine-1.2.0/jasmine.js"></script> <script type="text/javascript" src="testlib/jasmine-1.2.0/jasmine-html.js"></script> <!-- include source files here... --> <script type="text/javascript" src="/static_files/js/test-specs/main-nav-spec.js"></script> <!-- include spec files here... --> <script type="text/javascript" src="/static_files/js/common/jquery/latest.js"></script> <script type="text/javascript" src="/static_files/js/common/angular/angular-1.0.1.min.js"></script> <script type="text/javascript" src="/static_files/js/common/angular/angular-resource-1.0.1.min.js"></script> <script type="text/javascript" src="/static_files/js/section/main-nav-controller.js"></script> <script type="text/javascript"> (function() { var jasmineEnv = jasmine.getEnv(); jasmineEnv.updateInterval = 1000; var htmlReporter = new jasmine.HtmlReporter(); jasmineEnv.addReporter(htmlReporter); jasmineEnv.specFilter = function(spec) { return htmlReporter.specFilter(spec); }; var currentWindowOnload = window.onload; window.onload = function() { if (currentWindowOnload) { currentWindowOnload(); } execJasmine(); }; function execJasmine() { jasmineEnv.execute(); } })(); </script> </head> <body> </body> </html>
这是什么,我做错了?我不能理解这件事应该如何工作:)
你的测试代码的主要问题是它试图使用new操作符“手工”创建一个控制器的实例。当这样做AngularJS没有机会注入依赖。你应该做的是允许AngularJS注入依赖:
原文链接:https://www.f2er.com/javaschema/282393.htmlvar $scope,ctrl; //you need to inject dependencies first beforeEach(inject(function($rootScope) { $scope = $rootScope.$new(); })); it('Should initialize value to Loading',inject(function($controller) { ctrl = $controller('MainNavController',{ $scope: $scope }); expect($scope.wksp_name).toBe('Loading...'); }));
这里是一个完整的jsFiddle的链接:http://jsfiddle.net/pkozlowski_opensource/7a7KR/3/
在上面的例子中有两件值得注意的事情:
>您可以使用ngMock模块中的inject()方法注入依赖关系:https://docs.angularjs.org/api/ngMock/function/angular.mock.inject
>要创建一个控制器实例(支持依赖注入),您将使用$ controller服务:http://docs.angularjs.org/api/ng.$controller
最后一句话:我建议命名控制器以大写字母开头 – 这样我们不会把它们与变量名混淆。