Skip to content

Commit

Permalink
fix(component): reset form-bound captcha value after component destru…
Browse files Browse the repository at this point in the history
…ction

This fixes a potential mismatch between value that form controller (such as `FormGroup`) has, and the one represented by reCAPTCHA checkbox UI. This condition occurs when `<re-captcha>` gets destroyed (by, say, conditional *ngIf-rendering), and then gets re-initialized.

closes #201
  • Loading branch information
DethAriel committed Jul 22, 2021
1 parent 6d43a74 commit 0e550c4
Show file tree
Hide file tree
Showing 3 changed files with 149 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import { Component, NgZone } from "@angular/core";
import { ComponentFixture, TestBed } from "@angular/core/testing";
import { FormsModule, ReactiveFormsModule } from "@angular/forms";
import {
FormControl,
FormGroup,
FormsModule,
ReactiveFormsModule,
Validators,
} from "@angular/forms";
import { By } from "@angular/platform-browser";
import { BehaviorSubject } from "rxjs";

import {
RecaptchaComponent,
Expand All @@ -10,7 +17,7 @@ import {
} from "..";
import { MockRecaptchaLoaderService } from "./test-utils/mock-recaptcha-loader.service";

describe("RecaptchaValueAccessorDirective", () => {
describe("RecaptchaValueAccessorDirective -> [(ngModel)]", () => {
@Component({
template: `
<form #captchaForm="ngForm">
Expand Down Expand Up @@ -134,3 +141,111 @@ describe("RecaptchaValueAccessorDirective", () => {
expect(() => directive.onResolve("test value")).not.toThrow();
});
});

describe("RecaptchaValueAccessorDirective -> formGroup", () => {
@Component({
template: `
<form [formGroup]="formGroup" *ngIf="(loading$ | async) === false">
<re-captcha formControlName="captcha"></re-captcha>
</form>
`,
})
class TestComponent {
public loading$ = new BehaviorSubject<boolean>(false);
public formGroup = new FormGroup({
// eslint-disable-next-line @typescript-eslint/unbound-method
captcha: new FormControl(null, [Validators.required]),
});

public testHideForm(): void {
this.loading$.next(true);
}

public testShowForm(): void {
this.loading$.next(false);
}

public testSetCaptchaControlValue(value: string | null): void {
this.formGroup.setValue({ captcha: value });
}

public testGetCaptchaControlValue(): string | null {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return this.formGroup.controls["captcha"].value;
}
}

let fixture: ComponentFixture<TestComponent>;
let mockRecaptchaLoaderService: MockRecaptchaLoaderService;

beforeEach(async () => {
mockRecaptchaLoaderService = new MockRecaptchaLoaderService();
await TestBed.configureTestingModule({
declarations: [
RecaptchaValueAccessorDirective,
RecaptchaComponent,
TestComponent,
],
imports: [FormsModule, ReactiveFormsModule],
providers: [
{
provide: RecaptchaLoaderService,
useValue: mockRecaptchaLoaderService,
},
],
}).compileComponents();

fixture = TestBed.createComponent(TestComponent);
mockRecaptchaLoaderService.init();
fixture.detectChanges();

await fixture.whenStable();
});

it("should not try to reset the component if it has been destroyed already", () => {
// Arrange
mockRecaptchaLoaderService.grecaptchaMock.emitGrecaptchaResponse(
"test response"
);
fixture.detectChanges();

// Act
fixture.componentInstance.testHideForm();
fixture.detectChanges();

expect(fixture.componentInstance.testGetCaptchaControlValue()).toEqual(
"test response"
);
mockRecaptchaLoaderService.grecaptchaMock.reset.calls.reset(); // the "onDestroy" resets the captcha

fixture.componentInstance.testSetCaptchaControlValue(null);
fixture.detectChanges();

// Assert
expect(fixture.componentInstance.testGetCaptchaControlValue()).toBeFalsy();
expect(
mockRecaptchaLoaderService.grecaptchaMock.reset
).not.toHaveBeenCalled();
});

it("should reset the host if the control value written does not represent grecaptcha state", () => {
// Arrange
mockRecaptchaLoaderService.grecaptchaMock.emitGrecaptchaResponse(
"test response"
);
fixture.detectChanges();

// Act
fixture.componentInstance.testHideForm();
fixture.detectChanges();
expect(fixture.componentInstance.testGetCaptchaControlValue()).toEqual(
"test response"
);
fixture.componentInstance.testShowForm();
fixture.detectChanges();

// Assert
expect(fixture.componentInstance.testGetCaptchaControlValue()).toBeFalsy();
expect(mockRecaptchaLoaderService.grecaptchaMock.reset).toHaveBeenCalled();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,34 @@ export class RecaptchaValueAccessorDirective implements ControlValueAccessor {
/** @internal */
private onTouched: () => void;

private requiresControllerReset = false;

constructor(private host: RecaptchaComponent) {}

public writeValue(value: string): void {
if (!value) {
this.host.reset();
} else {
// In this case, it is most likely that a form controller has requested to write a specific value into the component.
// This isn't really a supported case - reCAPTCHA values are single-use, and, in a sense, readonly.
// What this means is that the form controller has recaptcha control state of X, while reCAPTCHA itself can't "restore"
// to that state. In order to make form controller aware of this discrepancy, and to fix the said misalignment,
// we'll be telling the controller to "reset" the value back to null.
if (
this.host.__unsafe_widgetValue !== value &&
Boolean(this.host.__unsafe_widgetValue) === false
) {
this.requiresControllerReset = true;
}
}
}

public registerOnChange(fn: (value: string) => void): void {
this.onChange = fn;
if (this.requiresControllerReset) {
this.requiresControllerReset = false;
this.onChange(null);
}
}
public registerOnTouched(fn: () => void): void {
this.onTouched = fn;
Expand Down
14 changes: 14 additions & 0 deletions projects/ng-recaptcha/src/lib/recaptcha.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,20 @@ export class RecaptchaComponent implements AfterViewInit, OnDestroy {
}
}

/**
* ⚠️ Warning! Use this property at your own risk!
*
* While this member is `public`, it is not a part of the component's public API.
* The semantic versioning guarantees _will not be honored_! Thus, you might find that this property behavior changes in incompatible ways in minor or even patch releases.
* You are **strongly advised** against using this property.
* Instead, use more idiomatic ways to get reCAPTCHA value, such as `resolved` EventEmitter, or form-bound methods (ngModel, formControl, and the likes).å
*/
public get __unsafe_widgetValue(): string | null {
return this.widget != null
? this.grecaptcha.getResponse(this.widget)
: null;
}

/** @internal */
private expired() {
this.resolved.emit(null);
Expand Down

0 comments on commit 0e550c4

Please sign in to comment.