【发布时间】:2015-07-30 08:20:08
【问题描述】:
我正在尝试对我的服务进行单元测试
在我的测试控制器中
myService.getItem('/api/toy/' + scope.id).success(
function(toy) {
$scope.toy = toys.details;
}
);
我的服务
angular.module('toyApp').service('myService', ['$http',
function($http) {
var service = {};
return {
getItem: function(url) {
return $http.get(url);
},
};
}
]);
测试文件。
describe('toy ctrl', function () {
var $httpBackend, ctrl, myService;
beforeEach(module('toyApp'));
beforeEach(inject(function (_$controller_, _$httpBackend_, _$rootScope_, __myService_) {
scope = _$rootScope_.$new();
$httpBackend = _$httpBackend_;
myService = _myService_;
ctrl = _$controller_('toyCtrl', {
$scope: scope
});
}));
describe('call my service', function() {
it('should make request when app loads', function() {
$httpBackend.expectGET('/api/toy/123').respond({id:123, detail:456 });
myService.getItem('/api/toy/123').then(function(toy){
expect(scope.toy.detail).toBe(456);
})
$httpBackend.flush();
})
})
我来了
Error: Unexpected request: GET /api/toy/123
No more request expected
如果我取出$httpBackend.flush(),错误就消失了,但它不会覆盖
function(toy) {
$scope.toy = toys.details;
}
部分。我想介绍函数调用,但不知道该怎么做。任何人都可以帮助我吗? 非常感谢
【问题讨论】:
-
你是在单元测试控制器还是服务(当应用加载看起来像控制器时应该发出请求)?
-
我正在控制器内部测试服务
-
好的。在这种情况下,您可以模拟您的服务并将其注入控制器。并针对范围测试价值。基本上我想说的是,当你对控制器进行单元测试时,你只需要测试控制器逻辑
myService.getItem('/api/toy/123')实际上是无关紧要的。 -
@PSL 你能举个例子吗? +1
标签: javascript angularjs unit-testing jasmine karma-jasmine