我測試了一個控制器,它有一個方法從我的服務器返回一個json對象。我真的很困惑如何對我的方法返回的期望。
我需要根據結果對我的範圍進行一些清理。
我想要完成的是調用search() - >查看返回的數據是什麼 - >以及如果長度== 0 - >確保我的範圍已刪除某些值。我怎樣才能檢查我的方法已返回?
$scope.clearIds = function(){
//clean out data I don't need anymore
}
$scope.search = function(inputValue, modelname, action, field){
modelname = modelname || 'companies';
action = action || 'search';
field = field || 'title';
return apiResource.query({api_resource:modelname, api_action:action, api_column:field, api_value:inputValue}).$promise.then(function(response){
if(response.data.length === 0){
$scope.clearIds();
}
else{
return response.data;
}
});
}
describe('Controller - TypeaheadSearch', function() {
// load the controller's module
beforeEach(module('app'));
var scope;
var apiResource;
var stateParams;
var q;
var deferred;
var rootScope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope, $q) {
apiResource = {
query: function() {
deferred = $q.defer();
deferred.resolve('bar');
return deferred.promise;
}
};
scope = $rootScope.$new();
stateParams = {};
q = $q;
rootScope = $rootScope;
$controller('TypeaheadSearch', {
$scope: scope,
$stateParams:stateParams,
apiResource: apiResource,
});
}));
it('Should call apiResource:query', function() {
spyOn(apiResource, 'query').and.callThrough();
scope.search();
rootScope.$apply();
expect(apiResource.query).toHaveBeenCalled();
});
});
更簡單的你可以做'apiResource = jasmine.CreateSpyObj('apiresource',['query']); apiResource.query.and.returnValue($ q.when(expectedQueryValue));' – PSL