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?
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