0

I am using the library react-google-recaptcha.

My component looks like this and runs fine from browser:

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"
      />
    </>
  }
}

I have tried to mock the recaptcha component like this stackoverflow post, this worked for the checkbox recaptcha fine, but how do I handle the invisible recaptcha.

Here is my test:

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();
  });
});

I get the following error:

TypeError: recaptchaRef.current.executeAsync(...).then is not a function

How do I mock the ref?

Matt Kuhns
  • 1,328
  • 1
  • 13
  • 26

1 Answers1

0

I suppose you have to mock the function implementation as a Promise;

As you know, async code must return promises and you have returned a string that doesn't have the then and or catch methods.

Try to change your mock with the code bellow

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;
});
Vagner Leitte
  • 861
  • 7
  • 12