Skip to content

Instantly share code, notes, and snippets.

@Bartuz
Last active July 7, 2020 06:16
Show Gist options
  • Save Bartuz/baa4cb3cff45286a519acc5ad0313bd7 to your computer and use it in GitHub Desktop.
Save Bartuz/baa4cb3cff45286a519acc5ad0313bd7 to your computer and use it in GitHub Desktop.
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
Copy link
Author

Bartuz commented Jul 7, 2020

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