AMA: Testing an Angular app

Ben asks…

I’ve been working with angular a while now but I have to admit, the testing side throws me. Every time I start to tackle it, I find myself distracted from the test I want to write by all of the things I need to mock. Sometimes it feels like I need to build an entire mock framework to test one feature. Maybe I’m doing it wrong. Any tips appreciated, whether practical or even just the right headspace for approaching it :)

My response…

I haven’t worked with angular applications directly but I’ve worked on React applications and I’m guessing the approach to unit testing these will be similar.

I would start as simple as possible with the smallest test that would possibly work. If you find that you need an entire mock framework to test a feature it sounds like your components may need to be broken down further into smaller components as you have too many dependencies that need to be mocked. If you have smaller components that only require a single dependency then these components should be easier to test as the dependencies will be easier to mock.

With smaller components I would also encourage you to be able to pass in dependencies. This allows you to easily mock/override dependencies for testing purposes – known as dependency injection. I wrote about this using a simple JavaScript example previously which you may want to read.

If retrofitting unit tests into your app is still too difficult you could try to automated some key end-to-end scenarios using Protractor, but I’d discourage you from going overboard since these can quickly get out of hand. You may still benefit from having a few of these tests even if you get unit testing of small components working well to ensure the small components work well together.

I hope this helps you Ben 😊