问题描述
如何在 ControleValueAccessor 内部使用时测试 ngFor 元素。
@Component({
selector: 'checkBox-group',templateUrl: `
<h3 class="tt">s</h3>
<ng-container *ngFor="let item of _model;let i = index" > <h3>s</h3>
<div>
<input type="checkBox" id="c{{i}}"/>
</div>
</ng-container>
`,providers: [
{
provide: NG_VALUE_ACCESSOR,useExisting: forwardRef(() => CheckBoxGroupComponent),multi: true
}
]
})
export class CheckBoxGroupComponent implements ControlValueAccessor {
constructor(private ref: ChangeDetectorRef) {
ref.detach();
}
writeValue(value: any): void {
this._model = value;
if(value != null) { this.ref.detectChanges();
}
}
从父 settings.html 导入这个控制值访问器:
<div>
<checkBox-group [(ngModel)]="selectedItems"></checkBox-group>
</div>
现在当我想测试它时,它只有一个子元素。并且只知道 tag 作为第一个和最后一个子元素
setting.spec.ts:
Testbed.configureTestingModule({
declarations: [ SettingsPage,CheckBoxGroupComponent ],imports: [IonicModule.forRoot()],providers: [
{
provide: NG_VALUE_ACCESSOR,multi: true
}
// other providers
],schemas: [ NO_ERRORS_SCHEMA ]
}).compileComponents();
it('should get checkBoxGroup Childs',fakeAsync(() => {
let customComponent = fixture.nativeElement.querySelector('checkBox-group');
component.selectedItems = [true,true,true];
fixture.detectChanges();
fixture.whenStable().then(() => {
customComponent.NgModule=[true,false,true];
fixture.detectChanges();
debugger;
});
}))
在 customComponent 上调试:
解决方法
我不完全确定你想做什么,但试试这个:
注意标有!!的评论
import { By } from '@angular/platform-browser';
....
TestBed.configureTestingModule({
declarations: [ SettingsPage,CheckboxGroupComponent ],imports: [IonicModule.forRoot()],providers: [
/* !! Get rid of these lines because CheckboxGroupComponent
is already doing the providing !!
{
provide: NG_VALUE_ACCESSOR,useExisting: forwardRef(() => CheckboxGroupComponent),multi: true
} */
// other providers
],schemas: [ NO_ERRORS_SCHEMA ]
}).compileComponents();
it('should get checkBoxGroup Childs',fakeAsync(() => {
component.selectedItems = [true,true,true];
fixture.detectChanges();
// !! We can queryAll of the CSS elements and expect the length to be 3
let customComponents = fixture.debugElement.queryAll(By.css('checkbox-group'));
expect(customComponents.length).toBe(3);
}))
!!编辑!!
<h3 class="tt">s</h3> // <-- this is the h3 you're seeing
<h1>Model's value: </h1>
<pre>{{ _model | json }}</pre>
<ng-container *ngFor="let item of _model;let i = index" > <h3>s</h3> // You want to see <h3>s</h3>
<div>
<input type="checkbox" id="c{{i}}"/>
</div>
</ng-container>
所以你是说你只看到了类为 tt
的 h3 而没有看到里面有 s 的 h3?
我添加了一个 h1
和一个 pre
标记来显示 _model
的值。看看它的值是什么,并确保它不是一个空数组。