我一直在玩下面的代码,但我找不到问题,测试失败,出现以下消息:"预期未定义而不是未定义。
我有一个服务,它向我的控制者返回承诺。在控制器中,我在解决承诺后立即使用 $q.all 做一些事情。
我试图遵循这个例子,但我看到的最大区别是,在示例中,它在控制器的根目录中有调用,我在方法"$scope"内有服务调用。客户测试",所以我在申请($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
注释控制器的第一个测试(it(.js其他两个测试工作。请帮忙吗?
解决了我在这里的问题,如果有人有类似的问题,希望它能有所帮助。
这是测试:
describe('CustomerController.js', function() {
var results = [{
"Id": 1,
"Name": "Mr"
}];
var $controller;
var $q;
var $rootScope;
var $scope;
var marketingService;
beforeEach(angular.mock.module('marketingApp'));
beforeEach(inject(function(_$rootScope_, $controller, _$q_,
_marketingService_) {
$scope = _$rootScope_.$new();
$q = _$q_;
$rootScope = _$rootScope_;
marketingService = _marketingService_;
$controller('customerController', {
$scope: $scope,
$rootScope: $rootScope
});
spyOn(marketingService, 'getTitleSuggested').and.callFake(function() {
var deferred = $q.defer();
deferred.resolve(results);
return deferred.promise;
});
}));
it('It should call the service" ', function() {
$scope.CustomerTest('Mr');
expect(marketingService.getTitleSuggested).toHaveBeenCalledWith('Mr');
});
it('It should populate the "$scope.TitlesTest" ', function() {
$scope.CustomerTest('Mr');
$rootScope.$apply();
expect($scope.hello).toEqual('Hello Mr Marcos');
expect($scope.Titles[0].Name).toBe('Mr');
expect($scope.Titles).toBe(results);
});
}(;
这是 plunker: http://plnkr.co/edit/3IMzqH1yKW8kazZFWaA0?p=preview