【发布时间】:2014-03-17 22:01:06
【问题描述】:
我正在使用我正在为其编写单元测试用例的服务。当我注入service 并从controller 调用函数时,我没有得到data。我是写案例的初学者。
这是我的代码。
状态列表服务
angular.module('myApp').factory('StatesList', ['$resource', function($resource) {
return $resource('/api/states');
}]);
控制器
$scope.statesList = function () {
StatesList.query(function (states) {
// Brings all states
$scope.states = states;
});
};
测试
describe('States List', function () {
var ctrl, scope, statesService;
beforeEach(function () {
module('myApp');
inject(function ($rootScope, $controller, StatesList) {
scope = $rootScope.$new();
statesService = StatesList;
ctrl = $controller('StatesCtrl', { $scope: scope, StatesList: statesService });
});
});
it('should have practice list to be null', function () {
console.log('List of States');
scope.statesList();
console.log(scope.states); // I don't see any data here
expect(scope.states).not.toBeNull();
});
WebStorm 中的输出
'List of States'
undefined
为什么不显示状态。通过使用POSTMAN可以看到数据。
【问题讨论】:
-
作为第一次失败,控制器也接收到服务,所以你需要:
{$scope: scope, StatesList: statesService}(当然还要在创建控制器之前分配服务)。 -
@JesusRodriguez 因为我对此很陌生......我添加了你的代码......但没有得到你的第二点......如何分配服务?
-
我正在使用我在问题中编辑的代码.....仍然给我结果...
undefined
标签: javascript node.js angularjs unit-testing jasmine