2013-12-13 10 views
7

をコントローラに注入された私は、オブジェクトトラフルータの決意を受け取るコントローラをテストしようとしている:AngularJS:モックオブジェクトはトラフルータの決意

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 

    ... 

}); 

私のテストはこのようになります:

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

    ... 
}); 

しかし最初の期待は失敗します。

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. 

私の仮定は、私が分離されたコントローラをテストするユニットだとして、ルータは解決機能を実行し、正しい値を割り当てるために変更がないことです。

order依存関係を模倣する方法はありますか?

は、私は解決のものを取り除くとOrderを注入し、コントローラ自体にOrder.current$scope.orderをインスタンス化することができます知っているが、私はresolveアプローチを維持したいと思います。

答えて

13

このようにCtrlキーのコンストラクタに独自の順序を入れてください。いくつかのテストの後、私はorder` `の値を変更したい場合はどう

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

    ... 
}); 

よろしく

+0

。それ、どうやったら出来るの? –

関連する問題