2016-10-06 18 views
5

Tôi muốn thêm phụ thuộc vào điều khiển của tôi trong một thành phần:

Đây là thành phần của tôi:

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

Bây giờ tôi chỉ muốn thử nghiệm này như sau:

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

    }); 
}); 

Nhưng tiếc ctrl.myId là undefined vì $ routeParams không tiêm đúng. Tại sao?

+0

thay đổi 'var ctrl = $ componentController ('myComponent', $ routeParams, null);' thành 'var ctrl = $ componentController ('myComponent', {$ routeParams}, null);' Cũng lưu ý, bạn có thể sử dụng thứ hai đối số để chèn một giả $ routeParams (xem Neo182 câu trả lời). – user2954463

Trả lời

0

Tôi có tình huống rất tương tự như bạn, googled cho một thời gian nhưng không tìm thấy hầu như không có gì, nhưng cuối cùng tôi giải quyết vấn đề bản thân mình: Đây là giải pháp cho trường hợp của bạn:

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

    }); 
}); 

Ngoài ra kiểm tra Mocking $routeParams in a test in order to change its attributes dynamically về mocking của $ routeParams.

+0

cảm ơn .. hoạt động .. – oezkany

1

Bạn dường như được tái định $routeParams đây:

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

Làm như sau nên giải quyết vấn đề của bạn (cũng lưu ý rằng bạn mong đợi id được và thuộc tính của $routeParams, không myId):

$routeParams = _$routeParams_; 
$routeParams.id = 42; 
Các vấn đề liên quan