Theory of Uniting Testing in Angular

I recently finished reading through an article on Unit Testing in Angular. The article was from the Infragistics website and in 3 parts it tried to demystify Unit Tests in Angular:

In this article, the author, Jared Fineman, really goes into how to setup your tests, how to structure tests and some of the great new features of Angular, that help with testing. One great point Jared makes is *In the world of development, unit tests have long been viewed as second-class citizens. * This is very true, it is something I have been guilty of too, forgetting that Unit Tests are an extremely important part of the development process. As part of my drive this year to improve the quality of my work, I’m focusing on both Unit Testing and readability, so I need to make writing test a core part of my development process.

In the first part of the article, Jared shows how to set up tests for your project. Though at the time of writing this version 6 of Angular was not released yet. So there is a section about updating the .angular-cli.json file, which has now been replaced by the angular.json file. Then in the other two parts of the article, Jared goes through structuring unit tests and some of the great features that Angular has that allow you to really explore the inner workings of your components. So you can write tests that examine all parts of the component.

The one that struck me in the second part of this article was the approach he mentions for structuring your unit tests. He mentions this AAA approach, which stands for Arrange, Act and Assert. The idea is that you first setup everything needed to run the component that is going to be tested, you basically arrange all the parts needed for the component. This could be modules that need to initialised, other parent components or mock data.
Next is the Act section, this is where you call the method or the component to be tested and from that call, the result can be examined. Finally, there is the Assert phase, where our assertions or expectations are tested.

This AAA methodology is great for learning how to set up tests, it is definitely something that isn’t documented enough in the official Angular docs. If a developer is new to Angular and they want to start writing tests for their app, the Angular docs do give a detailed overview of how to write a test for different scenarios. The new Angular docs really give a lot of examples, how to test components, how to test the DOM, how to test services and providers, but the theory of unit testing is not discussed enough in the documentation (but the Angular docs is open source, so maybe that can be changed).

There is, of course, articles about AAA outside of Angular, here are a few I found, though they are C# based the theory still applies:

There are a lot of articles about the Theory of Unit Testing, just not all Angular specific. It is worth searching around for them. This article from Jared Fineman is a great start.

When enough is enough,

There is a time when writing code that you need to say to yourself, enough is enough. I’m not talking about giving up coding, what I’m talking about is when you’ve been adding so many features to a section, that the code is unmanageable. There is a point where cramming in another feature to a section, means that the code behind will need to be re-written in order to make it easier to read, easier to manage and easier to test.

One of the big problems with AnglarJS, when it first became popular was developers didn’t know the best practices for how to write good clean AngularJS applications. The main problem was with the controller. The controller is a great concept, having a JavaScript file that sits behind your HTML template, which has access to all the elements in the template was amazing, but soon developers started to go crazy writing everything in one controller, at the time there wasn’t a ‘style guide’ that showed us a better way. Slowly over time, better practices were shared in the community, there were more examples of how to structure our AngularJS apps.

Recently I’ve had to work with an AngularJS project that has a controller where the structure of the controller has become unmanageable. Currently, the file has over 1200 lines of code, it is full of functions all doing different things, nothing grouped together in a logical structure, the use of both $scope and VM models is throughout the file instead of using one approach consistently. It is hard to work with this controller, and it is important of the functionality of the application.

Now I can see how this controller has gotten into this situation. It’s clear that at the beginning of the development this core piece of functionality that the controller manages was not fully planned. So the developer probably thought, this section doesn’t have a great deal of functionality I can keep it all within one controller.
Soon the features for this section grew and became more and more complex, the demand to get them delivered also grew, so the time for refactoring was not available. Now we are in a situation when we have a 1200 line controller that is hard to work with, nearly impossible to add new features too and is still buggy.

In order to stop this type of situation, developers need to be able to say to the PMs and stakeholders of a project, that they need to spend some time, refactoring the existing code in order to make it so new features can be added easily.

When a team successfully uses Scrum there is this time to raise issues like this, to let the PMs know that a bit of time is needed in order to tidy up the code before tackling a new feature. As part of the standard sprint planning, this can be raised. Without it the team just keep ploughing on building onto of existing code, adding feature after feature until everything is nearly unmanageable.

So what can developers and teams do in order to stop this happening:

  • Have regular sprint planning meetings to discuss the work coming up and not keep ploughing along without reviewing
  • Set out from the beginning a style guide, how the team will approach the development of the application
  • In PR reviews, don’t just have a quick look over the code and accept it, discuss with the developer if there are problems or code smells and how they can restructure their code to avoid these types issues later
  • Teach the more junior developers good practices on structuring code
  • Tell the managers and stakeholders why having good code quality is important to their project, why cutting corners, will only come back to haunt a project later on
Unit Testing and tight timescales

I’ve worked on a number of projects, where we’ve started the project with the idea to have 100% coverage with unit tests, but as soon as deadlines start to get closer, unit tests are the first to go.

What are the reasons for this?

There are several reasons why this happens, as the deadline for a project gets closer, you’re developers are put under more pressure to get all the features completed. So they need to focus on that, the time spent on updating or creating new Unit Tests is then spent on getting these features delivered.

If the project being developed in an internal project, and the stakeholder sees that the release deadline is getting closer, they are probably wondering why their developers are spending time writing tests and not being that new feature they have just asked for. I’ve seen this several times, the project manager or business owner, is under pressure to deliver and they hear a lot of talk from developers saying they need to write the tests for a feature, but to the PM that seems a waste of time. On one project we were asked to stop developing unit tests as we needed to get a version of the website ‘out the door’.

I’ve also been on projects where, as a team, it was decided to ‘come back and write the tests later’. As an approach to getting this high level of quality that the project needed. This wasn’t a good idea, as we never went back to write the tests and eventually the code coverage on the project was very poor.

Unit tests and test coverage are sometimes seen as nice things to have. We know as good developers we should have them, we should have tests for every line of code we write. There are many talks, books, podcasts, where ‘experts’ are telling us, developers, that you should be writing tests. It’s like when you are trying to eat healthily, you know you should make a salad for lunch, but those crisps and cheese rolls are just so much easier and quicker to make.

How can this problem be solved?

The central cause of this problem is time, projects basically run out of time to get all the features of a project completed and still write the tests. One solution to this problem is better planning up front. When scoping out a feature, developers need to see unit testing as an integral part of the development process. If they are using the points system in scrum to say what the effort involved in creating a new feature. Writing the unit tests needs to be considered as part of this effort and it is up to the senior members of the team to remind all the developers to include this unit test development as part of their estimates of effort.

Developers need to also show the Project Managers and stakeholders the importance of maintaining good test coverage is to not only to the project as it is now, but a year or two down the line, when a new feature of the site/app is going to be added to the project. When these new changes start to be developed for the project, the PM/stakeholder needs to know how important it is to have good tests during this ‘adding a new feature’ development phase is, in order to make sure the existing site/app doesn’t have bugs introduced.

As well as developers not adding the effort required to their scrum estimates, and PMs not aware of the importance of keeping tests up to date in a project, another issue is that writing test does take a long time, especially if you are just starting out writing tests.  I’ve worked on projects where when I was writing my unit tests I wasn’t convinced that the tests I was writing were actually ‘testing’ my code, but was probably just checking that a value is present. The quality of the tests was not very good..

As developers, we are shown all about the features of a new framework or library, how it does the new latest thing, how fast it runs and how it is better than framework X, but it is very little in the framework documentation on how to plan your tests? What approach should developers take when writing tests? We see many examples where a test suite is set up, and the test checks the value of a <span> in a template, or a test for an HTTP request of a static file, but there isn’t much information about the ‘theory’ of writing good unit tests. Have you tried writing tests for AngularJS directives? It’s easy to check the HTML of a directive, but testing the inner workings of your directive? Nearly impossible.

If developers spend the time learning about writing tests, and if the authors of these frameworks/libraries show others how to write good tests for their framework based apps. The time developers spend writing tests will be reduced. The more we practice something, the quicker and better we get.

If PMs and stakeholders can see unit tests and coverage as an investment into ensuring the quality of a project and the providing long-term support to a project, they will allow the developers to spend this extra time need to write tests.

Job hunting as a Contractor in todays world

I’ve been contracting now for nearly six years (it’ll be six years in July) and ever since I started I’ve been constantly going from one contract to the next. I’ve been lucky enough to only have one short spell of about 3 weeks where I didn’t have a contractor was waiting for one to start.

Does this mean I’m the best contractor out there or the most gifted Angular developer in the UK with companies just queuing to offer me the next contract? Well no, unfortunately, that’s not true. I’m a good Angular developer but I’m not Todd Motto.

What I have been, is good at job hunting.

I get most of my contracts through recruitment agencies, love them or hate them, you can’t live without them as a contractor. This means I speak to a lot of recruiters on the phone. The conversation usually goes something like this. ‘I have a role, it’s for a company in London, doing Web Development. They also have pizza and snacks. Now tell me everything about your last role’.
So what this translates to is, ‘we have a role, which you could be one of many CV’s I put forward. It’s actually in South West London, so that’s an extra 40 min tube journey for you, but we all know you developers love pizza. So you should be happy there as once or twice they have provided pizza (but you’ll have to work all night to get it). What I really want is the details of your last client so I can contact them and try to sell my recruiting services to them’.

So there are a lot of missing details here, where exactly is the role (if you have a 30 min train journey into London, another 40 min tube journey all adds up, are you prepared for that amount of travelling), what are they looking for, what skills is the client looking for. If the client wants a Java developer, but you’ve only used JavaScript, then it’s not a role for you. What is the day rate? This is extremely important to find out early, but it is a tricky part of the initial conversation with the agency.

The client must have a budget of how much they are will to pay a contractor, the agency takes a percentage of this day rate for their services, which is fine. You as a contractor are also running a business, your own limited company. This limited company comes with all the taxes and costs that any other business has. So you need to bring in enough money to cover those costs.

So there are 3 separate companies trying to make the best of a set budget. As a contractor, you need to think about your business needs first. This is why we have an ideal day rate, but the topic of day rates and setting them is something for another post. Back to the process of finding work as a contractor.

When I started contracting, all you really needed was a good CV and a phone. You’d upload your CV to JobServe, apply for a couple of contracts and the phone would soon start ringing. Then you have to speak to the agents, telling them what you’ve done before, how many years experience you have in a certain technology (which is never a good marker for technical knowledge, but its all they have) and what your availability for interviews is. That’s it, your CV went off to the client and if they wanted to see you, the agent would happily arrange it.

That’s how it was a few years ago, but like everything else related to the web, things have changed, fast. Now it is no longer enough to have a CV listing a few technologies and your recent 5 jobs. Clients want to know more, they want to see more about you as a developer. Thanks to sites like GitHub and BitBucket you can create your own portfolio of code. Your GitHub account is a window into seeing what type of developer you are, the type of projects you’re interested in, how you write your code, the way you structure your code. All this can be learnt through having a good Github account.

But does this mean without a GitHub account or one with a bar of green squares, you’re not a good developer? If you don’t spend all your waking hours committing code, does that mean you don’t know as much as someone who does? Well no, but for a recruitment agency it is all about numbers, the number of years you’ve been using a certain technology, the number of projects you have in GitHub, it’s all the same.

So as I said, in July it’ll be six years since I started contracting and now how I have to find jobs has changed. I know I have a good CV, it’s up to date, not to much waffle, it doesn’t just list technologies I’ve used. I’ve tried to describe the types of the projects I’ve worked on, what I did in these projects, but I know that I need to do more to promote myself as a developer.

I do need to add more to my GitHub account, show more of the code I write, I should get involved in open source, there are many benefits to working with open source for contracting developers. This is another great topic for a blog post.

The things to remember as a contractor when it comes to job hunting are:

– Have an up to date CV that you can send out quickly.
– Be able to talk/communicate well with recruiters, they are extremely helpful.
– Keep promoting yourself, your skill set, experience.
– Keep an eye on the job market, even if you are in a long-term contract. That way you know the current market rates, what people are looking for.
– Try to find out as much as you can from the agency, ask them loads of questions. The more you can learn, the more you’ll be sure the role is for you.

Interesting issue with Angular Material

I was recently starting a new Angular/Angular Material app, using the latest version of the CLI. Following along with the getting started guide I created my basic app, but as soon as I added a Material component I was getting errors that were stopping my app from running.

The error I was getting was:

node_modules/@angular/material/slide-toggle/typings/slide-toggle.d.ts(55,18): error TS2315: Type ‘ElementRef’ is not generic.

This is a strange and slightly misleading error. After a bit of digging around, I found a GitHub post where someone mentioned that if in your package.json file the version you have of Material is 6, but your version of Angular is 5 then this error is thrown.

Now, this is a simple issue to fix, thanks to the new ng update feature, all you need to do is run ng update and all the angular versions are up to 6. Rebuild your app and run ng serve and the app runs perfectly again.

This was a strange issue that I spent a little time looking into, but it does show how useful ng update is.

 

Material Starter Components, the hidden gem of Angular 6

Angular 6 was released just a few days ago and with it came a whole set of features, including Angular Elements, being able to update your app to use all the latest packages using the new ng update feature. There is also ng add which allows you to add new packages to your app using your chosen package manager, either npm or yarn (or whatever new one comes out in the next 6 months).

After reading through the new release blog post, one set of features that haven’t been getting as much exposure as say Angular Elements, was the new Material Starter Components, which are part of this release.

I like Angular Material, I think it gives a great polish to the UI. When I’m creating Angular apps having the UI handled by a library like Material or ng-bootstrap, really helped to get the development of the app moving quickly. So I was happy to see that in Angular 6 there are these Starter Components.

But what are these components, well they are just standard Material components that generate layouts for your app. If you’re building an app that requires a collapsible side nav, there is a new component that will generate that for you. Not just the Nav but the main container and the side navigation with a couple of demo links so you can quickly get started building upon the basic structure the component generates for you.

There is also a dashboard component, which generates a layout of a dashboard application with a section for various panels that the dashboard would use to display information in.  Again this can be generated using the standard ng generate command of the Angular Cli.

What I find really exciting about these Starter Components is that they can be built by teams who want to have their own layouts and share them with the Angular community. If you’re building an HR app in Angular and you need a layout for showing staff details, check to see if one has been built by someone in the community. If it’s there then all you need is one simple command in the CLI and you have the basic layout of your app generated for you ready to go.

The more of these Starter Components there are, the easier it will be for teams to get started building responsive, attractive looking UIs with Angular Material.

For further information of Material Starter Components, there is the official docs on Schematics, the functionality in the CLI that allows you to add Starter Components. There is also a video by Tina Gao who works on the Angular Material team, where she discusses the Material Tree component

Why Angular Developers Love NgRx

If you saw any of the recent talks from ngConf, you will probably have seen one on NgRx, it was a huge topic at the conference this year, but why are  Angular developers all talking about NgRx?

If you run a team of Angular developers they probably have already mentioned that they are looking to use NgRx in a project sometime soon, why? Well because NgRx solves one large problem, state management. What is state management, well it is a way of managing the state of an application between screens For example if you have a six-step process that needs to add to the application your team is building. In order to pass the information enter in step 1 to step 6, state management gives the developer a way of storing all the information added throughout each step, so it is accessible throughout the entire processes.

Before state management libraries like NgRx, developers use to have different approaches to store the state of the application, from storing all the information in local storage in the browser to cookies and even writing back to a temporary table in a database. With each project, there was probably another way of managing the state of the application.

This means when your developers are working on a project there wasn’t a common approach to the state management problem, but now thankfully due to libraries like NgRx, there is.

Another great feature of libraries like NgRx is the dev tools that come with the library. These ‘dev tools’ are features written into the library that take advantage of the wonderful features of a modern browser, by tapping into the tools the browser gives. Tools that allow the developer to really look into what is happening in the application as it runs. NgRx comes with a feature called store devtools this gives the developers the ability to add or amend the state of the application to see how the app handles different states. This is something that was usually done in the QA stage because it was easier to set up in QA. Now a developer can change the state through their browser to see how the app behaves. The better a developer can test how the app behaves at development time, the fewer bugs, the less time an app spend going through the QA process.

So to recap, Angular developers are loving NgRx at the moment, for two main reasons. One it gives them a standardised way to solve the problem of state management within an application, and two it helps provide fantastic tooling for developers to really look into how the application is working.

But NgRx isn’t the only state management library available, there is also NGXS which is another state management library for Angular. This one takes the approach to be more class-based, thanks to classes in TypeScript, than NgRx, which is more function based. Both tackle the same problem of state management, but NGXS has taken what people have learnt from using NgRx and implemented an approach that uses the great features of TypeScript.

If your team are looking at NgRx it is worth adding to your project, it will help your team with providing a common approach to one of the trickiest parts of building a modern web application.