我是 Angular 新手,我正在尝试在测试中获取 reCaptcha 令牌。如何模拟单击重新捕获“我不是机器人框”或类似的内容并在测试中记录令牌响应?我正在使用 reCaptcha 版本 2,并且尝试了一些到目前为止还没有起作用的变体。
index.component.html 片段:
<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方法:
@ViewChild('recaptcha', { static: false, read: RecaptchaComponent }) repactcha?: RecaptchaComponent
siteKey: string = environment.contactFormSiteKey
submitReCaptcha(token: any) {
//doing something here
测试类方法:
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);
})
如前所述,我对 Angular 还很陌生,并不完全理解我的测试方法中发生了什么。在这里获取 reCaptcha 令牌字符串的简单方法是什么??
在测试方法中我尝试过 debugEl.triggerEventHandler('click');但它并没有像其他一些排列那样做任何事情。
问题是
triggerEventHandler
采用另一个参数,即您想要模拟并传入的 $event
参数。
所以尝试以下方法:
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);