Javascript 单元测试控制器,angularJS和jasmine
嗨,我一直在尝试对控制器中的基本功能进行单元测试,但在设置单元测试时,我似乎无法连接 错误:[$injector:modulerr]未能实例化模块myApp,原因是: [$injector:nomod]模块“myApp”不可用!您要么拼错了模块名,要么忘记加载它。如果注册模块,请确保将依赖项指定为第二个参数 这是我的控制器:Javascript 单元测试控制器,angularJS和jasmine,javascript,angularjs,function,unit-testing,Javascript,Angularjs,Function,Unit Testing,嗨,我一直在尝试对控制器中的基本功能进行单元测试,但在设置单元测试时,我似乎无法连接 错误:[$injector:modulerr]未能实例化模块myApp,原因是: [$injector:nomod]模块“myApp”不可用!您要么拼错了模块名,要么忘记加载它。如果注册模块,请确保将依赖项指定为第二个参数 这是我的控制器: var myApp = angular.module("myApp", []); myApp.controller('studentController', fun
var myApp = angular.module("myApp", []);
myApp.controller('studentController', function($scope,$route,$routeParams,$http,$location){
//Get all students
$scope.getStudents = function(){
$http.get('/api/student/').then(function(response){
$scope.students = response.data;
});
};
还有我的测试:
describe("studentController", function () {
beforeEach(module('myApp'));
var $controller;
beforeEach(inject(function (_$controller_){
$controller = _$controller_;
}))
describe("studentController", function(){
it("should get student data", function (){
var $scope = {};
$scope.getStudents();
expect($scope.students.length).toBe(15)
})
})
});
我已经将这两个文件与angular-mocks.js一起包含在jasmine html文件中
非常感谢您提供的任何帮助您正在注入
$route
,但您没有加载ngRoute模块。加载文件angular-route.js并声明依赖项:
var myApp = angular.module("myApp", ['ngRoute']);
在调用getStudents时,必须先使用following在中创建控制器,然后在单元测试中使用HttpBackend服务对其进行模拟 控制器
var myApp = angular.module("myApp", []);
myApp.controller('studentController', function($scope, $route, $routeParams, $http, $location) {
//Get all students
$scope.getStudents = function() {
$http.get('/api/student/').then(function(response) {
$scope.students = response.data;
});
};
});
测试文件
describe("studentController", function() {
beforeEach(module('myApp'));
var $controller, scope, route;
beforeEach(inject(function(_$controller_, $rootScope, $route, $routeParams, $http, $location) {
$controller = _$controller_;
scope = $rootScope.$new();
$controller('studentController', {
'$scope': scope,
'$route': $route,
'$routeParams': $routeParams,
'$http': $http,
'$location': $location
});
}))
describe("studentController", function() {
it("should get student data", function() {
// for this you have to use httpBackend
// you have to mock the response of api
$scope.getStudents();
// then you are able to verify the result in student
expect($scope.students.length).toBe(15)
})
})
});
有关更多信息,请参阅和