0

I'm new to Angular and I'm trying to get the reCaptcha token in a test. How can I emulate click on the re-capture 'I am not a robot box' or something similar and logging the token response in a test? I'm using reCaptcha Version 2 and I've tried a few variations that's haven't worked so far.

index.component.html snippet:

<div class="d-flex justify-content-center">
    <re-captcha #recaptcha (resolved)="submitReCaptcha($event)" [siteKey]="siteKey" theme="dark" formControlName="recaptcha"></re-captcha>
</div>

index.component.ts method I'm testing:

@ViewChild('recaptcha', { static: false, read: RecaptchaComponent }) repactcha?: RecaptchaComponent
siteKey: string = environment.contactFormSiteKey

submitReCaptcha(token: any) {
    //doing something here

testing class method:

it('on click it should retrieve a token', () => {
    const fixture = TestBed.createComponent(IndexComponent);
    fixture.detectChanges(); //tell the TestBed to perform data binding

    const component = fixture.componentInstance; //access properties and methods
    const debug = fixture.debugElement; //test helper
    const native = fixture.nativeElement; //DOM

    var token = '';
    spyOn(component, 'submitReCaptcha').and.callFake((arg: any) => {
        token = arg;
    })

    const debugEl = debug.query(By.css('re-captcha'));

    const nativeEl = native.getElementsByTagName('re-captcha')[0];
    nativeEl.setAttribute('size', 'invisible');
    debugEl.triggerEventHandler('resolved');
    console.log(token);
})

As mentioned I'm pretty new to Angular and don't fully understand what's going on in my testing method. What's the easy way to get the reCaptcha token string here??

In the testing method I've tried debugEl.triggerEventHandler('click'); but it doesn't do anything as well as a few other permutations.

1 Answer 1

0

The issue is that triggerEventHandler takes another argument which is the $event argument you would like to mock and pass in.

So try the following:

const nativeEl = native.getElementsByTagName('re-captcha')[0];
// !! I am not sure what this line does or why it is here, so I commented it out.
// nativeEl.setAttribute('size', 'invisible');
// !! Add second argument here of 'my-awesome-token'
debugEl.triggerEventHandler('resolved', 'my-awesome-token');
// !! It should hopefully log out my-awesome-token here.
console.log(token);

Not the answer you're looking for? Browse other questions tagged or ask your own question.