Recently I added Google’s reCAPTCHA to my website to prevent bots and other spammers from submitting my forms and filling my database and inbox with spam form submissions. My website UI is built using Angular 7, and I was using ngx-captcha to add Google’s reCAPTCHA field to my forms. It is definitely one of the best and easiest to use third party Angular components to incorporate reCAPTCHA into your Angular applications. However, like many other third party Angular components I tried to use to incorporate reCAPTCHA into my site, I was getting errors while running my unit tests.

The main issue was that there was a timing issue between when Angular loaded and discarded the components and when Google’s remote reCAPTCHA script was able to load. I kept getting the error reCAPTCHA placeholder element must be an element or idin 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 seem to fix all my unit tests and have been passing ever since! Hopefully this helps someone out there looking for an answer to this very same question!