Skip to content

Instantly share code, notes, and snippets.

@Bartuz
Last active Jul 7, 2020
Embed
What would you like to do?
helper to test https://github.com/sarneeh/reaptcha How to unit test Reaptcha invisible recaptcha google jest enzyme
const Component = ({ onSuccess, onError, onExpire }) => {
const recapchaRef = useRef(null);
return (
<Reaptcha
ref={recapchaRef}
sitekey={RECAPTCHA_SITEKEY}
size="invisible"
badge="inline"
onRender={() => recapchaRef.current.execute()}
onVerify={token => onSuccess(token) }
onError={onError}
onExpire={onExpire}
/>
);
};
describe('Component', () => {
it('calls on success with token', () => {
mockGrecaptcha({ forceCallbackType: 'success', token: 'captcha-token' })
const onSuccessSpy = jest.fn()
render(<Component onsuccess={onSuccessSpy} />)
expect(onSuccessSpy).toHaveBeenCalledWith('captcha-token');
});
});
const nop = () => {};
const reaptchaCallbackName = (type) => {
switch (type) {
case 'success':
return 'callback'
break;
case 'error':
return 'error-callback'
case 'expire':
return 'expired-callback'
default:
throw `Unknown callback type ${type}. Supported types: success, error, expire`
}
}
export const mockGrecaptcha = ({ forceCallbackType = 'success', reset = nop, execute = nop, token = 'g-token' } = {}) => {
window.grecaptcha = {
ready: callback => callback(),
render: (_html, reaptchaConfig) => {
const callback = reaptchaConfig[reaptchaCallbackName(forceCallbackType)]
callback(token)
},
reset: reset,
execute: execute,
};
};
@Bartuz

This comment has been minimized.

Copy link
Owner Author

@Bartuz Bartuz commented Jul 7, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment