【发布时间】:2016-06-08 14:29:36
【问题描述】:
我正在尝试将 Karma 和 Jasmine 集成到我的项目中。
我从一个非常基本的测试开始,以确保我的控制器已定义并且 $scope 变量等于一个字符串 - 它按预期通过。
我的控制器也调用了一个执行 $http.get 的服务,在运行我的测试时,没有提及任何服务,我得到了错误:
Error: Unexpected request: GET /my/endpoint/
No more request expected
控制器:
define(['module'], function (module) {
'use strict';
var MyController = function ($scope, MyService) {
$scope.testScope = 'karma is working!';
MyService.getData().then(function (data) {
$scope.result = data.hour
});
};
module.exports = ['$scope', 'MyService', MyController ];
});
测试:
define(['require', 'angular-mocks'], function (require) {
'use strict';
var angular = require('angular');
describe("<- MyController Spec ->", function () {
var controller, scope;
beforeEach(angular.mock.module('myApp'));
beforeEach(inject(function (_$controller_, _$rootScope_) {
scope = _$rootScope_.$new();
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!');
});
});
});
是否会出现上述错误?
更新以下回复:
define(['require', 'angular-mocks'], function (require) {
'use strict';
var angular = require('angular');
describe("<- MyController Spec ->", function () {
var controller, scope, $httpBackend, myService;
beforeEach(angular.mock.module('myApp'));
beforeEach(inject(function (_$controller_, _$rootScope_, _$httpBackend_, _myService_) {
scope = _$rootScope_.$new();
$httpBackend = _$httpBackend_;
$httpBackend.expectGET("/my/endpoint");
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 请求。而且您还没有配置 $httpBackend 来响应这样的请求。所以这个请求确实是出乎意料的。
标签: angularjs unit-testing jasmine karma-jasmine angularjs-service