terug naar overzicht

02/04/17

Insight insight

Applicatieontwikkeling

Daan Stolp

+31 35 539 09 09


02/04/17

Creating an AngularJS Component Using TDD

Learning Test-Driven Development (TDD) can be a great way to improve your skills as a professional software developer or, dare I say, software craftsman. There is a lot to learn about TDD as a process, and taking up the practice can be challenging at first. Once you master the basics, you sometimes just run into small technical obstacles. You know what you want to do, you just need to know how to do it.

Learning Test-Driven Development (TDD) can be a great way to improve your skills as a professional software developer or, dare I say, software craftsman. There is a lot to learn about TDD as a process, and taking up the practice can be challenging at first. Once you master the basics, you sometimes just run into small technical obstacles. You know what you want to do, you just need to know how to do it. In this article, I’ll discuss one such specific obstacle that I recently had to overcome myself: how to test-drive the development of an AngularJS component?rnrnComponents were introduced in Angular 1.5 in order to make the transition to Angular 2 easier and to promote the component-based architectural style. I find components to be a clean and intuitive way to develop complex application in AngularJS, and TDD to be a very helpful practice, so naturally I want to be able to test-drive the development of components!rnrnWhen writing a test for an AngularJS component, there are several challenges to solve: how to make the component available in your unit tests? How to get access to the controller that is used by the component? How to spy on dependencies of this component controller? And how to deal with promises that these dependencies might return?rnrnThere are a lot of different ways to solve this. As AngularJS evolves, testing approaches evolve with it. Apart from that, there are usually ten different ways to accomplish the same thing in AngularJS anyway, so finding one that works for you can be challenging. With that in mind, this article shows you just one possible approach that works for me.rnrnIn order to illustrate this approach, we’ll be creating a component for a simple calculator app. To make things a bit more challenging, the calculator will use an Angular service that performs the actual calculation, and return the result as a promise. In a real application, a component might also deal with services that fetch data from an API, or perform long-running operations that return promises.

Delen