0

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

How to mock reCaptcha to simulate user operation pending / reCaptcha failed / reCaptcha passed ?

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. 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)

ch4mp
  • 6,622
  • 6
  • 29
  • 49
  • The error I get is fixed with this answer https://stackoverflow.com/a/45660571/619830. Will come back in a few days with polished RecaptchaFormComponent mock (going offline at sea...) – ch4mp Sep 19 '19 at 17:57

1 Answers1

0

Here is the code I use to mock 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.');
  }

}
ch4mp
  • 6,622
  • 6
  • 29
  • 49
  • Could you please add the usage of this mock class in a test file? I have troubles integrating it in my test file. – Shaunyl May 20 '20 at 11:08