我想在组件中向我的 Controller 添加依赖项:
这是我的组件:
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 没有被正确注入(inject)。为什么?
最佳答案
我和你的情况非常相似,用谷歌搜索了一段时间但几乎什么也没找到,但最后我自己解决了这个问题:这是你的案例的解决方案:
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关于 $routeParams 的模拟。
关于angularjs - 单元测试时如何在 Angular 1.5 中向 $componentController 添加依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39895969/