2016-10-06 6 views
5

मैं एक घटक में मेरी नियंत्रक के लिए उनकी निर्भरता को जोड़ना चाहते हैं, जबकि:

angular 
    .module('app') 
    .component('myComponent', { 
    template: '<div>some content</div>', 
    controller: ["$routeParams", function ($routeParams) { 
     var ctrl = this; 
     ctrl.myId = $routeParams.id; 
    }); 

अब मैं सिर्फ परीक्षण करना चाहते हैं:

यहाँ मेरी घटक है इस का पालन:

describe("spec for myComponent", function() { 

    var $componentController; 
    var $routeParams; 

    beforeEach(module('app')); 
    beforeEach(inject(function (_$componentController_, _$routeParams_) { 
    $componentController = _$componentController_; 
    $routeParams = _$routeParams_; 
    $routeParams = { 
     myId: 42 
    } 
    })); 

    it('should init', function() { 

    var ctrl = $componentController('myComponent', $routeParams, null); 

    expect(ctrl.myId).toBe(42); 

    }); 
}); 

लेकिन दुर्भाग्य से ctrl.myId क्योंकि $ routeParams सही ढंग से इंजेक्शन नहीं कर रहे हैं अपरिभाषित है। क्यूं कर?

+0

बदलें 'var ctrl = $ घटक नियंत्रक (' myComponent ', $ pathParams, null); 'var ctrl = $ घटक नियंत्रक (' myComponent ', {$ pathParams}, null);' यह भी ध्यान दें, आप दूसरे का उपयोग कर सकते हैं एक नकली $ रूट पैराम इंजेक्ट करने के लिए तर्क (Neo182 देखें जवाब है)। – user2954463

उत्तर

0

मैं तुम्हारा के रूप में बहुत इसी तरह की स्थिति थी, थोड़ी देर के लिए googled लेकिन लगभग कुछ भी नहीं पाया है, लेकिन अंत में मैं अपने आप को समस्या हल:

describe("spec for myComponent", function() { 

    var $componentController; 
    var mockRouteParams = {id : 1}; 

    beforeEach(module('app')); 

    beforeEach(inject(function (_$componentController_) { 
    $componentController = _$componentController_; 
    })); 

    it('should init', function() { 

    var ctrl = $componentController('myComponent', {$routeParams:mockRouteParams}, null); 

    expect(ctrl.myId).toBe(1); 

    }); 
}); 

इसके अलावा Mocking $routeParams in a test in order to change its attributes dynamically के बारे में मजाक की जाँच: यहाँ अपने मामले के लिए समाधान है $ मार्ग पैराम्स का।

+0

धन्यवाद .. काम करता है .. – oezkany

1

आप फिर से परिभाषित करने के लिए यहाँ $routeParams हो रहे हैं: कर

$routeParams = _$routeParams_; 
$routeParams = { 
    myId: 42 
} 

आपकी समस्या का समाधान (यह भी ध्यान दें कि आप id हो सकता है और $routeParams की विशेषता के लिए उम्मीद, myId नहीं) चाहिए निम्नलिखित:

$routeParams = _$routeParams_; 
$routeParams.id = 42; 
संबंधित मुद्दे