【发布时间】:2015-01-20 23:24:55
【问题描述】:
我正在尝试测试一个控制器,而不是要求我模拟我用来获取数据的服务。目前我收到一条错误消息,提示此行上的函数未定义:
dataServiceMock = jasmine.createSpyObj('dataService', ['getFunctionStuff']);
根据其他示例和教程,这应该可以正常工作。
这是我的代码,包括测试文件、服务和控制器。
控制器:
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope, dataService) {
dataService.getFunctionStuff($scope.foo)
.then(function(data) {
$scope.test = data;
});
});
服务:
app.factory('dataService', function ($timeout, $q){
function getFunctionStuff(formData) {
return $http.post('../randomAPICall', formData).then(function(data) {
return data;
});
};
});
测试:
describe('Testing a controller', function() {
var $scope, ctrl, $timeout;
var dataServiceMock;
beforeEach(function (){
dataServiceMock = jasmine.createSpyObj('dataService', ['getFunctionStuff']);
module('myApp');
inject(function($rootScope, $controller, $q, _$timeout_) {
$scope = $rootScope.$new();
dataServiceMock.getFunctionStuff.and.ReturnValue($q.when('test'));
$timeout = _$timeout_;
ctrl = $controller('MainCtrl', {
$scope: $scope,
dataService: dataServiceMock
});
});
});
it('should update test', function (){
expect($scope.test).toEqual('test');
});
});
这是它的一个小插曲:http://plnkr.co/edit/tBSl88RRhj56h3Oiny6S?p=preview
【问题讨论】:
-
我已经发布了两种进行单元测试的方法。一种是你创建间谍的方式,另一种是使用
$httpBackend,这是一种常见的方式。
标签: angularjs unit-testing jasmine