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?