2013-12-13 13 views
7

sto cercando di testare un controllore che riceve la risolutezza di un router attraverso oggetto:AngularJS: oggetto Mock iniettato al controllore determinazione del router attraverso

app.js:

... 
.when('/confirm', { 
    templateUrl: 'views/confirm.html', 
    controller: 'ConfirmCtrl', 
    resolve: { 
    order: function(Order) { 
     return Order.current; 
    } 
    } 
}) 
... 

ConfirmCtrl.js:

angular.module('angularGeolocationApp').controller('ConfirmCtrl', 
function($scope, order, ...) { 

    $scope.order = order 

    ... 

}); 

Il mio test è simile al seguente:

'use strict'; 

describe('Controller: ConfirmCtrl', function() { 

    // load the controller's module 
    beforeEach(module('angularGeolocationApp')); 

    var ConfirmCtrl, 
    scope; 

    // Initialize the controller and a mock scope 
    beforeEach(inject(function ($controller, $rootScope) { 
    scope = $rootScope.$new(); 
    ConfirmCtrl = $controller('ConfirmCtrl', { 
     $scope: scope 
    }); 
    })); 

    it('should get an order object', function() { 
    expect(_.isObject(scope.order)).toBeTruthy(); 
    }); 

    ... 
}); 

Tuttavia prima aspettativa fallisce:

PhantomJS 1.9.2 (Mac OS X) Controller: ConfirmCtrl should get an order object FAILED 
    TypeError: Attempted to assign to readonly property. 
     at workFn (/Users/jviotti/Projects/Temporal/angular/angular-geolocation/app/bower_components/angular-mocks/angular-mocks.js:2107) 
    Expected false to be truthy. 

La mia ipotesi è che, come io sono unità di testare il controller isolato, il router non ha un cambiamento per eseguire la funzione determinazione e assegnare il valore corretto.

C'è un modo per deridere la dipendenza da order?

So che posso sbarazzarsi della roba determinazione e iniettare Order e istanziare $scope.order al Order.current nel controller stesso, ma mi piacerebbe mantenere l'approccio resolve.

risposta

13

Basta inserire il proprio ordine nel costruttore del ctrl come questo.

describe('Controller: ConfirmCtrl', function() { 

    // load the controller's module 
    beforeEach(module('angularGeolocationApp')); 

    var ConfirmCtrl, 
     scope, 
     order 


    // Initialize the controller and a mock scope 
    beforeEach(inject(function ($controller, $rootScope) { 
    order = {}; 
    scope = $rootScope.$new(); 
    ConfirmCtrl = $controller('ConfirmCtrl', { 
     $scope: scope, 
     order: order 
    }); 
    })); 

    it('should get an order object', function() { 
    expect(_.isObject(scope.order)).toBeTruthy(); 
    }); 

    ... 
}); 

riguarda

+0

Che cosa succede se, dopo alcune prove, voglio cambiare il valore di 'order'. Come lo faccio? –

Problemi correlati