我可能做错了,但我不知道如何解决它。
我想测试一个使用资源 (ngResource) 的控制器,并且我想使用 Spy 作为资源的测试替身,因此它实际上并不执行 http 调用。在下面的代码中,我只想测试控制器中的搜索功能。
控制器:
controllers = angular.module('app.controllers');
controllers.controller('landingCtrl', ['$scope', '$q', 'categoryResource', function ($scope, $q, categoryResource) {
$scope.search = function (text) {
console.log('searching for: ' + text);
var deferred = $q.defer();
categoryResource.query({ searchTerm: text }, function (result) {
if (result.length == 0) {
deferred.resolve(['No results found']);
} else {
deferred.resolve(result);
}
});
return deferred.promise;
}
}]);
服务:
var services = angular.module('app.services');
services.factory('categoryResource', ['$resource', function ($resource) {
var resource = $resource('/api/category');
return resource;
}]);
登陆Ctrl的规范:
describe('Controller: landingCtrl ', function () {
var $q,
$rootScope,
$scope;
beforeEach(module('ngResource'));
beforeEach(module('app.services'));
beforeEach(module('app.controllers'));
beforeEach(inject(function (_$rootScope_, _$q_) {
$q = _$q_;
$rootScope = _$rootScope_;
}));
// mock any depencencies, like scope. $resource or $http
beforeEach(inject(function ($controller, $injector, categoryResource) {
$scope = $rootScope.$new();
spyOn(categoryResource, 'query').andCallFake(function (searchText) {
console.log('query fake being called');
var deferred = $q.defer();
deferred.resolve(['Test', 'Testing', 'Protester']);
return deferred.promise;
});
landingCtrl = $controller('landingCtrl', {
'$scope': $scope,
'$q': $q,
'categoryResource': categoryResource
});
}));
afterEach(inject(function ($rootScope) {
$rootScope.$apply();
}));
it('should return words with "test" in them"', function () {
$scope.search('test').then(function (results) {
console.log(results);
expect(results).toContain('Test');
});
$scope.$apply();
});
});
测试执行没有错误,但它没有解决承诺就通过了,所以我在“then”函数中的代码永远不会被调用。我究竟做错了什么?
我已经创建了一个具有上述内容的 plunker 和一个应该失败的测试: