【发布时间】:2016-02-26 09:55:11
【问题描述】:
我正在尝试测试来自控制器内执行的服务 http 调用的响应:
控制器:
define(['module'], function (module) {
'use strict';
var MyController = function ($scope, MyService) {
var vm = this;
$scope.testScope = 'karma is working!';
MyService.getData().then(function (data) {
$scope.result = data.hour
vm.banner = {
'greeting': data.greeting
}
});
};
module.exports = ['$scope', 'MyService', MyController ];
});
单元测试:
define(['require', 'angular-mocks'], function (require) {
'use strict';
var angular = require('angular');
describe("<- MyController Spec ->", function () {
var controller, scope, myService, serviceResponse;
serviceResponse= {
greeting: 'hello',
hour: '12'
};
beforeEach(angular.mock.module('myApp'));
beforeEach(inject(function (_$controller_, _$rootScope_, _MyService_, $q) {
scope = _$rootScope_.$new();
var deferred = $q.defer();
deferred.resolve(serviceResponse);
myService = _MyService_;
spyOn(myService, 'getData').and.returnValue(deferred.promise);
controller = _$controller_('MyController', {$scope: scope});
scope.$apply();
}));
it('should verify that the controller exists ', function() {
expect(controller).toBeDefined();
});
it('should have testScope scope equaling *karma is working*', function() {
expect(scope.testScope ).toEqual('karma is working!');
});
});
});
如何测试http 请求是否已执行并返回绑定到$scope.result 和vm.banner greeting 的serviceResponse
我试过了:
define(['require', 'angular-mocks'], function (require) {
'use strict';
var angular = require('angular');
describe("<- MyController Spec ->", function () {
var controller, scope, myService, serviceResponse, $httpBackend;
serviceResponse= {
greeting: 'hello',
hour: '12'
};
beforeEach(angular.mock.module('myApp'));
beforeEach(inject(function (_$controller_, _$rootScope_, _MyService_, _$httpBackend_) {
scope = _$rootScope_.$new();
$httpBackend = _$httpBackend_
$httpBackend.expectGET("/my/endpoint/here").respond(serviceResponse);
myService = _MyService_;
spyOn(myService, 'getData').and.callThrough();
controller = _$controller_('MyController', {$scope: scope});
scope.$apply();
}));
it('should call my service and populate scope.result ', function() {
myService.getData();
expect(scope.result ).toEqual(serviceResponse.hour);
});
it('should verify that the controller exists ', function() {
expect(controller).toBeDefined();
});
it('should have testScope scope equaling *karma is working*', function() {
expect(scope.testScope ).toEqual('karma is working!');
});
});
});
出现错误:
[should call my service and populate scope.result ----- Expected undefined to be defined.
【问题讨论】:
-
我认为您应该使用
whenGET而不是expectGET来模拟响应。此外,您还错过了对$httpBackend.flush();的调用来满足异步请求。但在我看来,您应该在两个单独的测试中进行测试,而不是一个。 -
你能提供
MyService的代码吗? -
@LouieAlmeda - 向服务提供代码无关紧要,因为我没有测试服务,它只执行获取并返回一些数据,然后我将其绑定到 $scopes。
标签: angularjs unit-testing jasmine karma-jasmine angularjs-controller