Жасмин тест с угловой нг-макет не работает с контроллером и обещание

Я немного поигрался со следующим кодом и не смог найти проблему, тест не пройден со следующим сообщением: "Ожидается, что undefined не будет неопределенным".

У меня есть служба, которая возвращает обещание моему контролеру. В контроллере я использую $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);
});

И это плункер

http://plnkr.co/edit/3IMzqH1yKW8kazZFWaA0?p=preview

Комментируя первый тест (it) controller.spec.js, два других теста работают. Любая помощь, пожалуйста?

1 ответ

Решение

Решил мою проблему, вот снова плунжер, если у кого-то есть подобная проблема, надеюсь, это поможет.

Вот тест:

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);
});

});

и это плункер: http://plnkr.co/edit/3IMzqH1yKW8kazZFWaA0?p=preview

Другие вопросы по тегам