我目前面临的情况是,我必须测试一个组件,该组件包含另一个组件,该组件有自己的 UT 隔离。像这样:
<parent-component>
<div>
<child-component form-data="formData"></child-component>
</div>
</parent-component>
在测试用例之前,我编译传递作用域参数的元素及其模板:
beforeEach(inject((_$q_, _$rootScope_, $compile) => {
$q = _$q_;
$rootScope = _$rootScope_;
$scope = $rootScope.$new();
makeComponent = (scopeParam, template) => {
const componentTemplate = template || defaultTemplate;
const scope = _.merge($scope, scopeParam);
element = $compile(angular.element(componentTemplate))(scope);
scope.$apply();
};
makeController = (params, template) => {
makeComponent(params, template);
return element.controller(component.name);
};
}));
它引用的范围参数之一 formData
被传递给 child-component
并且每当更改时(在 parent- 的 $onInit 上) component
事实上),child-component
的 $onChanges
被触发并监听这个变化导致调用一个方法从我的端点检索一些数据分别在其 UT 中进行模拟。
问题是我想避免在 parent-component
上渲染这个 child-component
并在 UT 的唯一目的是测试时复制测试逻辑组件逻辑分开。我怎么才能让 UT 只测试这个父组件并丢弃它上面的任何嵌套组件?
最佳答案
我用一个解决方案来回答自己。这个想法是使用 decorators
来修改现有类的行为而不修改代码本身。了解更多:https://docs.angularjs.org/guide/decorators .我们唯一需要做的就是实例化我们的模拟模块并传递 $provide
并使用我们的组件名称调用 decorator
方法,同时传递 'Directive' $delegate
包含组件/服务,然后才能向提供商注册。我们只需要设置一个自定义模板和 Controller ,在这种情况下:emtpy 值,并返回它。就这样,子组件将作为其空 Controller 的空模板,我们可以专注于测试孤立的父组件。
beforeEach(angular.mock.module(module, ($provide) => {
$provide.decorator('myComponent' + 'Directive', ($delegate) => {
const comp = $delegate[0];
comp.template = '';
comp.controller = class {};
return $delegate;
});
});
关于javascript - 在 Angular 1.5 中不编译嵌套组件的情况下测试组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44137911/