首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >模仿不可见的Google Recaptca

模仿不可见的Google Recaptca
EN

Stack Overflow用户
提问于 2022-01-08 00:15:46
回答 1查看 439关注 0票数 0

我正在使用库react google-recaptcha

我的组件如下所示,在浏览器中运行良好:

代码语言:javascript
复制
const MyRecaptchaComponent = ({setRecaptchaToken}: {setRecaptchaToken: () => void}) => {
    const recaptchaRef = createRef<any>();
    function asyncScriptOnLoad() {
      recaptchaRef.current.executeAsync().then((value: any) => {
        setRecaptchaToken(value, 'score');
      });
    return (
    <>
      <ReCAPTCHA
        size="invisible"
        ref={recaptchaRef}
        sitekey="MyValidSiteKey"
        asyncScriptOnLoad={asyncScriptOnLoad}
        data-testid="invisible-mock-v2-captcha-element"
      />
    </>
  }
}

我尝试过像这个堆叠溢流柱一样模拟recaptcha组件,这对于复选框recaptcha很好,但是我如何处理不可见的recaptcha。

这是我的测试:

代码语言:javascript
复制
import CheckboxRecaptcha from '../CheckboxRecaptcha';
import ReCAPTCHA from 'react-google-recaptcha';

jest.mock('react-google-recaptcha', () => {
  const RecaptchaV2 = React.forwardRef<any, any>((props, ref) => {
    React.useImperativeHandle(ref, () => ({
      executeAsync: () => 'token',
    }));
    return (
      <input
        ref={ref}
        type="checkbox"
        onClick={() => {
          props.asyncScriptOnLoad();
        }}
        {...props}
      />
    );
  });

  return RecaptchaV2;
});

describe('test', () => {
  it('should', () => {
    const props = {
       setRecaptchaToken: jest.fn()
    };
    const component = render(<CheckboxRecaptcha {...props} />);
    fireEvent.click(screen.getByTestId('invisible-mock-v2-captcha-element'));
    expect(props.setRecaptchaToken).toHaveBeenCalled();
  });
});

我得到以下错误:

代码语言:javascript
复制
TypeError: recaptchaRef.current.executeAsync(...).then is not a function

我该怎么嘲笑裁判?

EN

回答 1

Stack Overflow用户

发布于 2022-11-30 19:52:48

我想你必须把函数的实现当作一个承诺来嘲弄;

如您所知,异步代码必须返回承诺,并且返回了一个没有then和或catch方法的字符串。

尝试用下面的代码更改模拟

代码语言:javascript
复制
jest.mock('react-google-recaptcha', () => {
  const RecaptchaV2 = React.forwardRef<any, any>((props, ref) => {
    React.useImperativeHandle(ref, () => ({
      // Check this ----------v
      executeAsync: () => Promise.resolve('token')
    }));
    return (
      <input
        ref={ref}
        type="checkbox"
        onClick={() => {
          props.asyncScriptOnLoad();
        }}
        {...props}
      />
    );
  });

  return RecaptchaV2;
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70628568

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档