我一直在使用以下代码,但找不到问题,测试失败并显示以下消息:“预期未定义未定义。”
我有一个服务,它向我的控制器返回一个承诺。在控制器中,我在得到承诺后立即使用 $q.all 做一些事情。
我尝试按照这个示例进行操作,但我看到的最大区别是,在示例中它在控制器的根目录中有调用,并且我在方法“$scope.CustomerTest”中有服务调用,所以我有这个附加行到应用之前( $scope.$apply() )“$scope.CustomerTest('Mr');”:
http://www.bradoncode.com/blog/2015/07/13/unit-test-promises-angualrjs-q/
这是我的测试代码:
var $scope;
var $q;
var deferred;
var $httpBackend;
//Inject the module "before each test"
beforeEach(angular.mock.module('marketingApp'));
beforeEach(inject(function ($controller,_$httpBackend_, _$rootScope_, _$q_, marketingService) {
$q = _$q_;
$scope = _$rootScope_.$new();
$httpBackend = _$httpBackend_;
// We use the $q service to create a mock instance of defer
deferred = _$q_.defer();
// Use a Jasmine Spy to return the deferred promise
spyOn(marketingService, 'getTitleSuggested').and.returnValue(deferred.promise);
// Init the controller, passing our spy service instance
$controller('customerController', {
$scope: $scope,
marketingService: marketingService
});
}));
it('should resolve promise', function () {
// Setup the data we wish to return for the .then function in the controller
var titles = [{ "Id": 1, "Name": "Mr" }];
deferred.resolve(titles);
$httpBackend.when('GET', '/MarketingCustomers/GetTitleSuggested')
.respond(200, titles);
//I call to the controller method here.
$scope.CustomerTest('Mr');
$scope.$apply();
// Since we called apply, not we can perform our assertions
//expect($scope.TitlesTest).not.toBe(undefined);
expect($scope.SelectedCustomerTitle).toEqual('Mr');
//expect($scope.error).toBe(undefined);
});
这是plunker:
http://plnkr.co/edit/3IMzqH1yKW8kazZFWaA0?p=preview
评论 controller.spec.js 的第一个测试(它),其他两个测试有效。请问有什么帮助吗?