AngularJs unit test - издеваемое обещание не исполняет "тогда" - программирование
Подтвердить что ты не робот

AngularJs unit test - издеваемое обещание не исполняет "тогда"

Мы тестируем наши контроллеры. Мы успешно издевались над вызовом на наш сервисный уровень REST и подтвердили, что он действительно вызывается с данными. Теперь, однако, мы хотели бы проверить, что в нашем контроллере выполнение обещания then изменяет location.path:

контроллер:

(function () {

    app.controller('registerController', ['$scope', '$location', '$ourRestWrapper', function ($scope, $location, $ourRestWrapper) {

    $scope.submitReg = function(){
        // test will execute this
        var promise = $ourRestWrapper.post('user/registration', $scope.register);

        promise.then(function(response) {    
                console.log("success!"); // test never hits here           
                $location.path("/");
        },
            function(error) {
                console.log("error!"); // test never hits here
                $location.path("/error");
            }
        );
    };

$ourRestWrapper.post(url,data) просто обертывает Restangular.all(url).post(data)..

Наш тест:

(function () {

    describe("controller: registerController", function() {

        var scope, location, restMock, controller, q, deferred;

        beforeEach(module("ourModule"));

        beforeEach(function() {
            restMock = {
                post: function(url, model) {
                    console.log("deferring...");
                    deferred = q.defer();    
                    return deferred.promise;
                }
            };
        });

        // init controller for test
        beforeEach(inject(function($controller, $rootScope, $ourRestWrapper, $location, $q){
            scope = $rootScope.$new();
            location = $location;
            q = $q;

            controller = $controller('registerController', {
                $scope: scope, $location: location, $ourRestWrapper: restMock});
        }));

    it('should call REST layer with registration request', function() {
        scope.register = {data:'test'};

        spyOn(restMock, 'post').andCallThrough();

        scope.submitReg();

        deferred.resolve();

        // successfull
        expect(restMock.post).toHaveBeenCalledWith('user/registration',scope.register);
        expect(restMock.post.calls.length).toEqual(1);
        // fail: Expected '' to be '/'.
        expect(location.path()).toBe('/');
    });

В нашей консоли мы видим "отсрочку...", и первые два ожидания преуспевают. Почему он не будет вызывать блок then (т.е. Установить местоположение)?

4b9b3361

Ответ 1

Загрузите объект $rootscope, когда вы получите его из инжектора, и вызовите $rootScope.$apply() сразу после deferred.resolve().