Your first unit test using Angular CLI, Karma and WebStorm

This is a guest blog post prepared by Pete Heard.
Pete is a full-stack JavaScript developer who has spent over a decade learning to craft robust software using Test Driven Development and advanced Object Oriented Design. He is the founder of Logic Room, a consultancy that helps organisations create enterprise web and mobile software.

In this article we will use WebStorm 2016.3 with its built-in support for the Angular CLI and Karma test runner. We will write a single unit test which will show you how to mock a service and check that your component works before integrating your changes!

What we will cover:

Setting up your application

1. Install Node.js

Okay, first off let’s make sure you have downloaded and upgraded to the latest and greatest of Node.js by going here.

2. Install Angular CLI

Angular CLI is a wrapper around some tools (for example, Webpack) that you need to create, build and deploy an Angular 2 application. WebStorm offers an integration with Angular CLI that allows you to create a new Angular 2 project and generate new components, directives, and services from the IDE.

We want to get a shiny new copy of Angular CLI on our machine, so enter the following into a terminal window:
npm install -g angular-cli

3. Create an Angular 2 project with Angular CLI

Open WebStorm and click Create new project on the IDE Welcome screen. You will be given an option to start a new Angular CLI project.

1__image

Choose this option, fill in the details and WebStorm will kick off a CLI command ng init --name=MyFirstTest. Wait for WebStorm and the CLI to finish (notice the output in the tool window for indication and a line which reads ‘done’).

4. Set up Karma

Karma is a JavaScript test runner which means it will read code in a certain format (in our case written in Jasmine) and run it as a suite of tests. WebStorm provides neat integration with Karma, and our Angular project already has an initial configuration required to use Karma.

This setup is done through the common interface of the Karma configuration file called karma.conf.js. This file will tell Karma which locations the tests are in, which reporting mechanism to use, and which browser to use to execute the tests. Here is an example Karma config file from the Angular CLI project:

Now we need to configure WebStorm to invoke Karma and pass it the config when we want to run our tests. This is really easy – we need to create a new Karma run/debug configuration. Go to Run – Edit Configurations from the menu.

Next, click the plus icon and select Karma from the list.

6_image

Enter the name as Test, then choose the configuration file (project/karma.conf.js). In the box that says Karma package, make sure you set the correct path to the Karma module in the project’s node_module folder.

7_image

Click OK to apply those settings and exit. Then simply click Run – Test and your tests will execute from WebStorm!

8_image

We have now finished configuring WebStorm for use with Angular 2 and have a simple project ready to go.

Writing Our First Unit Test (And Stubbing a Service)

We are ready to write our test and some code! We are going to create a very simple unit test which will check that some value is extracted from an Angular 2 service and that this value is then attached to our component (which is known as a fixture

11_image

1. Add The Skeleton Service and its Test Double

Make two files my-service.ts and my-fake-service.ts and place them in the app folder. The code for each one is below.

src/app/my-service.ts – the skeleton of the real service is needed for type safety!

src/app/my-fake-service.ts – the fake service is going to help us check that our component works.

2. Update the Test File with Dependencies and a Test

Since Angular 1 we have seen the use of modules. These are high-level containers that house our individual features. Angular 2 has this concept too and in order to test any component we need to load it into a module beforehand. This is done (in part) by a handy built-in helper class called TestBed.

In the file src/app/app.component.spec.ts, we need to stub the dependency for the service in the TestBed configuration and then we will add the unit test.

We aren’t going to dig around in the view of the component to make our assertions. Instead we are going to check the instance of the component as this will be cleaner. We will check the componentinstance variable.

We are going to add our imports, new test and a provider declaration. The code listing below shows where to add them. Your code should look exactly like the following:

src/app/app.component.spec.ts

Tip: on large-scale projects, avoid digging around in views. Instead, create clean objects (viewmodels) that sit on your component and then check them, as this will keep your tests focused and increase the lifespan of your test suite. The views can be tested in isolation.

Once you have added this new code, you should see that the message property on the component is red. Hooray! We are at the red part of our red/green refactor cycle. You can run the test now and it will fail. In fact technically it won’t ever run since it won’t pass the compile stage, and a test that doesn’t compile is the same as a failing test!

Tip: Enable Auto-run option in the Karma tool window (second icon in the left pane) to re-run tests automatically as you make changes in your code.

3. Make the Test Pass (and Compile)

First, we need to get rid of these compile errors. Let’s start by adding a message property into our component called
message.

src/app/app.component.ts

Go back and run the test. Our test is still looking for something that doesn’t exist. Notice that we get the following:

Okay, so now let’s go in and actually get the test passing. We do this by injecting our service into the component. But to do that, we need to also import the type. Your code should now look exactly as follows (notice the added reference to the service):

src/app/app.component.ts

Note: At this point you might be wondering why this.message in src/app/app.component.ts” is highlighted red. The reason is that the TypeScript service doesn’t yet know what the return type is and can’t tell at the moment that we have only implemented test code. When we wire up our final dependency, this will disappear.

Integrating Your Changes

Okay, you are now a bonafide TDDist, and when you do TDD well you should just be able to fire up your application and it will work first time. But let’s remember that we configured our dependency from a test context. We still need to wire up its real world counterpart. This involves 2 steps:

STEP 1: Update the real service my-service.ts to actually return something from its
getMessage function.

src/app/my-service.ts

In the real world we wouldn’t have much untested code (such as with the real service). We are just learning how to mock/stub the service.

STEP 2: Add the dependency to the app.module.ts.

src/app/app.module.ts

STEP 3: Add The Property Onto The View

Finally, just add the property onto the view:
src/app/app.component.html

Now just use WebStorm integrated npm menu to start the application. On the left-hand side double-click start in the npm tool window.

13_image

The application will launch. Then go to the url as shown below.

10_image

Conclusion

In this article we have learned a standardized and consistent way to create new Angular 2 using Angular CLI in WebStorm and to write and run unit tests with Karma.

Then we had a little TDD adventure and saw how to use a test double in place of a real service using Dependency Injection. We checked that an Angular 2 component was working with a stub which was set up from the test context. Then we wired up our real dependency and integrated our changes and ran the browser to check the final output.

I hope you have enjoyed this article. Happy clean-coding!

About Ekaterina Prigara

Ekaterina Prigara is WebStorm product marketing manager at JetBrains. She's passionate about new technologies, UX and coffee.
This entry was posted in Tutorials and tagged , , . Bookmark the permalink.

4 Responses to Your first unit test using Angular CLI, Karma and WebStorm

  1. David Aspinall says:

    Ekaterina,

    I have been a regular user of WebStorm for web client apps for some time, most recently with AngularJS. Now I am plunging into Angular 2 with Angular CLI.

    Here I am having no luck using your Angular CLI integration. I don’t get past first base:

    On the New Project menu, whatever I put for the Angular CLI path, I cannot get an enabled Create button. I think to date I have tried all folders in my CLI (global) installation.

    Note that I am running on Windows 10 with the latest version of NodeJS, NPM, Angular2…
    In particular I am installing Angular CLI with:

    npm install -g @angular/cli

    rather than the usual

    npm install -g angular-cli

    This reflects more recent instructions on the Angular-CLI GitHub. As usual, actual explanation (i.e. what, why, …) of any difference is nowhere to be found.

    Any pointer you can give will only help. In the meantime I have no problem running
    WebStorm and a command terminal side-by-side. But it seems a shame. I also cannot
    add any CLI components to an existing CLI project.

    Regards,

    David

  2. Ekaterina Prigara says:

    Hi David,

    Thank you for your comment.
    Angular CLI changes very quickly and we’re struggling a bit with incorporating the changes on our side on time.
    In the next WebStorm 2017.1 Early access preview update coming later this week WebStorm will be able to detect the CLI installed with npm install -g @angular/cli.
    Unfortunately, the option to generate components is also broken due to some issue on the CLI side. We have reported the issue on their tracker and are waiting for the fix. Here you can find more details: https://youtrack.jetbrains.com/issue/WEB-24735

  3. Daniel Bartholomae says:

    Hi Ekaterina,

    do you by any chance also have code coverage running with Angular 2 and Webstorm? I’ve had no luck with that yet and I’m actually not sure if it is currently possible.

    Best,
    Daniel

Leave a Reply

Your email address will not be published. Required fields are marked *