2013-07-30 84 views
0

這裏是我的茉莉花規範,如何使用RequireJS測試AngularJS控制器?

define(['app', 'angular', 'angularResource', 'angularMocks'], function() { 
describe('App module tests', function(){ 
    var module, $rootScope, scope, AppCtrl; 
    beforeEach(function() { 
     module = angular.module("MyApp"); 
     inject(function($rootScope, $controller){ 
      // The injector unwraps the underscores (_) from around the parameter names when matching 
      scope = $rootScope.$new(); 
      AppCtrl = $controller('AppCtrl', {$scope: scope}); 
     }); 
    }); 
    }); 
}); 

在我app.js,我有..

var MyApp = angular.module('MyApp'); 
MyApp.controller('AppCtrl', ['$rootScope', function($rootScope){ 
// controller code here 
}]); 

當我運行單元測試,我得到以下錯誤,

錯誤:參數'AppCtrl'不是一個函數,得到了undefined

另外,這裏是我的test-main.js,

var tests = Object.keys(window.__karma__.files).filter(function (file) { 
    return (/Spec\.js$/).test(file); 
}); 
requirejs.config({ 
    // Karma serves files from '/base' 
    baseUrl: '/base/src', 
    paths: { 
     'angular': 'libs/angular', 
     'angularResource': 'libs/angular-resource', 
     'angularMocks': 'libs/angular-mocks', 
     'app': 'app/app' 
    }, 
    // ask Require.js to load these files (all our tests) 
    deps: tests, 
    // start test run, once Require.js is done 
    callback: window.__karma__.start 
}); 

我的人緣配置,

// list of files/patterns to load in the browser 
files = [ 
    JASMINE, 
    JASMINE_ADAPTER, 
    REQUIRE, 
    REQUIRE_ADAPTER, 
    'src/libs/angular.js', 
    'src/libs/angular-resource.js', 
    'src/libs/angular-mocks.js', 
    {pattern: 'src/app/*.js', included: false}, 
    {pattern: 'src/app/**/*.js', included: false}, 
    {pattern: 'test/**/*Spec.js', included: false}, 
    'test/test-main.js' 
]; 

回答

2

試試這個。我認爲你需要擺脫包裝inject()的函數。

define(['app', 'angular', 'angularResource', 'angularMocks'], function() { 
    describe('App module tests', function() { 
     var module, $rootScope, scope, AppCtrl; 
     beforeEach(angular.module("MyApp")); 

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

Editied:

我認爲你需要ANGULAR_SCENARIO_ADAPTER果報工作。

+0

嘗試了這種方法,仍然得到相同的錯誤。 – Chandra

+0

我認爲你需要ANGULAR_SCENARIO_ADAPTER與業力一起工作。 – zsong

相關問題