正如我在这个答案中描述的那样,我创建了一个自定义 ControlValueAccessor 指令来控制何时触发我的组件的 onChange 事件,并且一切正常,除非我对其进行测试,否则永远不会调用 registerOnChange,因此我的测试失败。
我的指令如下所示:
export const MASK_CONTROL_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MaskDirective),
multi: true
};
@Directive({
selector: "[testMask]",
providers: [MASK_CONTROL_VALUE_ACCESSOR]
})
export class MaskDirective implements ControlValueAccessor {
private onChange;
private nativeElement;
constructor(private element: ElementRef) {
this.nativeElement = this.element.nativeElement;
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
}
setDisabledState(isDisabled: boolean): void {
this.nativeElement.disabled = isDisabled;
}
writeValue(newValue) {
newValue = newValue == null ? "" : newValue;
this.nativeElement.value = newValue;
}
@HostListener("input", ["$event"])
onInput(event: KeyboardEvent) {
/*DO YOUR STUFF HERE*/
// Call onChange to fire the valueChanged listeners
this.onChange(newValue);
}
}
我的测试:
describe("Test Custom Directive", () => {
@Component({
template:
`<input type="text" [formControl]=inputFormControl testMask/>`
})
class TestComponent {
_inputFormControl: FormControl;
constructor(private element: ElementRef) {
this._inputFormControl = new FormControl();
}
get inputFormControl() {
return this._inputFormControl;
}
}
let fixture: ComponentFixture<TestComponent>;
let inputField: HTMLInputElement;
const getInput = (fix: ComponentFixture<TestComponent>) => {
const inputDebug = fix.debugElement.query(By.directive(MaskDirective));
return inputDebug.nativeElement as HTMLInputElement;
};
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
TestComponent,
MaskDirective
]
});
});
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
inputField = getInput(fixture);
});
it("test", async () => {
//Tests fails because there's no onChange callback
});
}
根据我在“在 Angular 表单中实现 ControlValueAccessor 时不再感到困惑”中所读到的内容,我假设只是将 FormControl 添加到我的输入字段就应该触发 setupControl,但显然情况并非如此。我错过了什么?