Angular testing made easy

Eudes Petonnet
Mar 15, 2017 · 6 min read

Update 08/15/2017

A more up-to-date version of the code from this article is available here:


Let’s open your new toys

Jasmine’s user context

Did you know that Jasmine binds all the functions declared in it, beforeEach andafterEach to the same object when running a test? This object allows you to share information across the different phases of your test, and the object gets properly destroyed at the end of each test to avoid memory leaks.

Typing a function’s context

The previous example is fine, but all the nice tools you get from using Typescript instead of Javascript disappear when you work with an abstract this that comes from Jasmine. It is automatically typed as any, so you will not get any form of autocompletion, type checking or smart navigation in your IDE.

Time to put them together

Introducing the TestContext

If we want to extract all the boilerplate into a separate file, we need to decide what the type of the user context passed around by Jasmine should be. Since the configuration, component creation, element querying and teardown can all be tied to just the act of “creating a component”, we’ll expose a single create method that will handle all this. Then of course, we’ll want access to all the queried native elements and component instances, so we’ll need to expose these too. Using type parameters to make sure it can work on any directive to test and any test host wrapping it, we obtain this:

Making it available in tests

We have the interface, we can now type the user context. But just typing it won’t do much if don’t actually implement the create method somewhere… Let’s expose a function that will add it to the user context in a beforeEach that should be called before anything else:

The final spec file

Let’s remove all the boilerplate from the user component’s spec file and use our brand new context:

  • allow passing extra directives to declare or modules to import, in case your component depends on other ones,
  • add additional shortcuts to the TestContext interface,
  • throw explicit errors when trying to test with a host component that does not contain the directive,

Clarity Design System

Clarity is an open source design system that brings together UX guidelines, an HTML/CSS framework, and Angular components. Visit our website here: http://clarity.design

Eudes Petonnet

Written by

Tech lead of Project Clarity: @VMwareClarity

Clarity Design System

Clarity is an open source design system that brings together UX guidelines, an HTML/CSS framework, and Angular components. Visit our website here: http://clarity.design