模拟 Angular JS 控制器 Jasmine
Mock Angular JS Controller Jasmine
我是 angular js 的新手..刚刚构建了一个示例控制器..现在想对其进行单元测试..不确定如何在 jasmine 中编写模拟它..
TestApp.js
var TestApp = angular.module('TestApp');
TestApp.controller('TestCtrl', function($scope) {
$scope.test = "test";
});
})();
TestApp_Spec.js
var scope, ctrl;
//you need to inject dependencies first
beforeEach(inject(function($rootScope) {
$scope = $rootScope.$new();
}));
it('test value should be test', inject(function($controller) {
ctrl = $controller('TestCtrl', {
scope: $scope
});
expect(scope.test).toBe("test");
}));
我正在使用独立版本的 jasmine,并在 sepc_runner.html
中包含 angular.min.js、angular.mocks.js、TestApp.js 和 TestApp_Spec.js
测试结果未显示..
在编写正确的测试用例方面需要帮助..
您的代码中有一些修复,例如您没有在测试服中插入模块,因此 jasmine 无法找到 controller
。
您没有传递第二个参数,它是一个数组作为模块中的依赖项,即 angular.module('TestApp',[]);
app.js
(function(){
var TestApp = angular.module('TestApp',[]);
TestApp.controller('TestCtrl',["$scope",function(scope) {
alert(scope)
scope.test = "test";
}]);
})();
测试服
var scope, ctrl;
describe('MyApp', function() {
beforeEach(module('TestApp'));
//you need to inject dependencies first
beforeEach(inject(function($controller,$rootScope) {
scope = $rootScope.$new();
$controller('TestCtrl', {
'$scope': scope
});
}));
it('test value should be test',function(){
expect(scope.test).toBe("test");
});
});
我是 angular js 的新手..刚刚构建了一个示例控制器..现在想对其进行单元测试..不确定如何在 jasmine 中编写模拟它..
TestApp.js
var TestApp = angular.module('TestApp');
TestApp.controller('TestCtrl', function($scope) {
$scope.test = "test";
});
})();
TestApp_Spec.js
var scope, ctrl;
//you need to inject dependencies first
beforeEach(inject(function($rootScope) {
$scope = $rootScope.$new();
}));
it('test value should be test', inject(function($controller) {
ctrl = $controller('TestCtrl', {
scope: $scope
});
expect(scope.test).toBe("test");
}));
我正在使用独立版本的 jasmine,并在 sepc_runner.html
中包含 angular.min.js、angular.mocks.js、TestApp.js 和 TestApp_Spec.js测试结果未显示..
在编写正确的测试用例方面需要帮助..
您的代码中有一些修复,例如您没有在测试服中插入模块,因此 jasmine 无法找到 controller
。
您没有传递第二个参数,它是一个数组作为模块中的依赖项,即 angular.module('TestApp',[]);
app.js
(function(){
var TestApp = angular.module('TestApp',[]);
TestApp.controller('TestCtrl',["$scope",function(scope) {
alert(scope)
scope.test = "test";
}]);
})();
测试服
var scope, ctrl;
describe('MyApp', function() {
beforeEach(module('TestApp'));
//you need to inject dependencies first
beforeEach(inject(function($controller,$rootScope) {
scope = $rootScope.$new();
$controller('TestCtrl', {
'$scope': scope
});
}));
it('test value should be test',function(){
expect(scope.test).toBe("test");
});
});