我正在尝试为Angular 1.5中的组件编写单元测试.我想对该组件及其dom节点进行单元测试.该组件包含一个非常复杂的子组件.
我的目标是在不编译子组件的情况下对外部组件进行单元测试.
由于我也想测试DOM,因此使用$ componentController进行此测试是不够的.
这是我想要实现的一个简短示例:
组件代码:
angular.module('app').component('myComponent', {
bindings: {
username: '<',
},
template: `
<span>{{ $ctrl.username }}</span>
<my-complex-component />
`
controller: function () {}
});
Run Code Online (Sandbox Code Playgroud)
我的组件的单元测试:
it('my-component should render username', function () {
var template = '<my-component username="username"></my-component>',
element,
scope,
date;
scope = $rootScope.$new();
scope.username = 'John';
element = $compile(template)(scope);
scope.$digest();
username = element.find('span');
expect(username.text()).to.be.equal('John');
});
Run Code Online (Sandbox Code Playgroud)
我的复杂组件不应该被实例化.它应该在模板中抵制.在单元测试中创建元素应该导致
<span>John</span>
<my-complex-component />
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?
我正在开发一个custom-select内部使用本机 html 选择的 Angular 组件。的模板实现custom-select如下所示:
<!-- custom-select.component.html -->
<select class="select" [(ngModel)]="selectedId" (change)="onChange()">
<option *ngFor="let question of questions" [value]="question.id">{{ question.text }}</option>
</select>
Run Code Online (Sandbox Code Playgroud)
所以有一个change内部选择的处理程序。
对于我的自定义选择组件,我希望有一个名为 的输出绑定change。所以自定义选择组件对应的 TS 文件如下所示:
@Component({
selector: 'custom-select',
templateUrl: './custom-select.component.html'
})
export class CustomSelectComponent implements OnInit {
@Input() options: Array<{ id: string, text: string }>;
@Output() change = new EventEmitter<string>();
selectedId = '';
constructor() { }
onChange() {
this.change.emit(this.selectedId);
}
}
Run Code Online (Sandbox Code Playgroud)
现在我可以使用我的自定义选择,例如:
<custom-select [options]="options" (change)="onChange($event)"></custom-select>`
Run Code Online (Sandbox Code Playgroud)
如果我这样做,选择更改处理程序将被调用两次。看来第一个电话就是我期待的电话。第二个调用似乎是由内部选择更改处理程序触发的。
如果我将 custom-select 的处理程序重命名为selectChange,一切都会正常工作。 …
我有一个带有路由和延迟加载模块的 Angular 6 应用程序。AppModule 有一个路由配置,其中包含两个延迟加载的路由,例如 AModule 和 BModule。
我们为生产和开发配置了不同的 angular-cli 环境。
在 BModule 的开发过程中,我希望 BModule 可作为我们的开发服务器上的路由,但不能在我们的生产服务器上。
因此,我们使用 angular-cli 环境 dev 构建应用程序的开发版本,而生产版本则使用环境 prod 构建。
因此,现在和将来,通常会有一个 prod 的路由配置和一个 dev 的路由配置,这是 prod 配置的超集。
所以我所做的是创建了两个路由配置:
export const prodRoutes: Routes = [
{ path: 'a-module', loadChildren: `app/a-module/a.module#AModule` },
];
export const devRoutes: Routes = [
{ path: 'b-module', loadChildren: `app/b-module/b.module#BModule` },
];
Run Code Online (Sandbox Code Playgroud)
对于产品,我只需使用变量prodRoutes进行路由配置。效果很好。
对于开发配置,我将路由设置为[...devRoutes, ...prodRoutes]. 那不能正常工作。Angular 似乎不理解合并路由配置。
有没有办法将多个路由阵列合并到单个工作路由配置中?