Last active
July 7, 2020 06:16
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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} | |
/> | |
); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
main thread: jsardev/reaptcha#94 (comment)