Recently I added Google’s reCAPTCHA to my website to prevent bots and other spam. My website UI is built using Angular and ngx-captcha to add Google’s reCAPTCHA field to my forms. It is a great third party option for Angular components to incorporate reCAPTCHA. However, like many other third party reCAPTCHA components, I was getting errors while running my unit tests. In this post I’ll show how to unit test in Angular with Google reCAPTCHA.
The main issue was a timing issue between when Angular loaded components and when reCAPTCHA script was able to load. I kept getting the error reCAPTCHA placeholder element must be an element or id
in various test suites and test cases every time I would run my Jasmine unit tests, and every few runs, all tests would actually pass! I couldn’t figure out the issue for the life of me.
Then I submitted an issue to the component’s Github repository seeing if the author had any idea why this may be occurring. He suggested to try and fix the timing issue by waiting a period of time and then calling component.detectChanges()
. So I added the following to my beforeEach()
method in the unit test files where I was using the ngx-captcha
component and the parent components that directly encompassed the Angular component using ngx-captcha
.
function sleep(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}......beforeEach(async(done) => {
fixture = TestBed.createComponent(ContactFormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
await sleep(750);
done();
});
Luckily this seems to fix all my unit tests and have been passing ever since! Hopefully, this helps someone out there looking for an answer to unit testing issues in Angular With Google reCAPTCHA!