[英]How-to mock `<re-captcha>` in unit-test for a component using ng-recaptcha V2 in a reactive-form?
I'm using ng-recaptcha V2 in a reactive form and can't figure out how to write my unit tests for a component quite similar to doc sample for reactive forms: https://github.com/DethAriel/ng-recaptcha/#example-forms我正在以反应形式使用 ng-recaptcha V2,并且无法弄清楚如何为与反应 forms 的文档样本非常相似的组件编写单元测试: https://github.com/DethAriel/ng-recaptcha/ #example-forms
How to mock reCaptcha to simulate user operation pending / reCaptcha failed / reCaptcha passed?如何模拟 reCaptcha 以模拟用户操作挂起/reCaptcha 失败/reCaptcha 通过?
I tried many different ways.我尝试了很多不同的方法。 The one that seams the most promising is skipping
RecaptchaModule
and RecaptchaFormsModule
imports in test and creating a ReCaptchaComponentMock
component.最有希望的是在测试中跳过
RecaptchaModule
和RecaptchaFormsModule
导入并创建一个ReCaptchaComponentMock
组件。 But I can't get it working because of Error: No value accessor for form control with name: 'recaptcha'
("recaptcha" being the formControlName
value for my tag)但我无法让它工作,因为
Error: No value accessor for form control with name: 'recaptcha'
(“recaptcha”是我的标签的formControlName
值)
Here is the code I use to mock reCaptcha V2:这是我用来模拟 reCaptcha V2 的代码:
@Component({
selector: 're-captcha',
template: `
<input type="checkbox" (click)="toggleStatus()" checked="{{isValid}}">
<div class="status">{{status}}</div>`,
styles: [],
providers: [
{ provide: NG_VALUE_ACCESSOR, multi: true, useExisting: forwardRef(() => MockReCaptchaComponent) },
],
})
export class MockReCaptchaComponent implements ControlValueAccessor {
@Input() id: string;
@Input() siteKey: string;
@Input() tabIndex: number;
@Output() resolved = new EventEmitter<string>();
isValid: boolean = null;
status: string = null;
private change;
private touch;
toggleStatus() {
this.writeValue(this.isValid ? null : true);
this.status = this.isValid ? 'reCaptcha passed' : 'You robot!';
this.touch();
this.change(this.isValid);
if (this.isValid) {
this.resolved.emit('reCaptha-token');
} else {
throwError('robot');
}
}
execute(): void {
throw new Error('Method not implemented.');
}
reset(): void {
}
writeValue(obj: any): void {
this.isValid = obj;
}
registerOnChange(fn: any): void {
this.change = fn;
}
registerOnTouched(fn: any): void {
this.touch = fn;
}
setDisabledState?(isDisabled: boolean): void {
throw new Error('Method not implemented.');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.