Using Stubs and Mocks in Jasmine to test your Angular code

Setting up your environment and is a very important part of unit testing AngularJS code. We discuss some of the tools and methods under which we can provide the full workflow of a system under test in this post.

Intro

Unit tests allow us to automatically test our code under a variety of conditions to prove that it works and when it breaks it does so in expected ways. In order to predictably test code, we also need to completely control the setup and data provided to the code under test.

Thankfully, the test tools provided for Angular testing allow you to mimic your models and control how your code responds to code in a very precise way. Jasmine provides some easy way to create test doubles and even “spy” on their execution.

In this post we will discuss some of the best practices and tools we use to control the environment your code is working against.

Why do we need to fake stuff?

We need to control the entire environment and workflow to make sure we are testing the exact scenarios.

Messing around with the DB and creating fake records can be difficult at best, at worst it can create false positives. Even more common, some CI systems lack access to a DB at all

We also need the ability to re-create the conditions under which a bug has been created. sometimes this means we need to replicate some crazy conditions

There are two tools to make this happen: Test Stubs (also known as  Fakes, depending on who you ask) and Mock Objects:

  • Test stubs are a very simplified object or data structure designed specifically for the test scenario. These can be constructed at the beginning of the test or per test.
  • Mock objects are class instances that mimic an existing class to provide the same method interface and return specific values when a method call occurs.

Test Stubs in AngularJS & Jasmine

Test stubs are a simple data structure or model we rely on when running our tests. These can be as simple as a static array of data or a very lightweight object with publically scoped methods. To differentiate a stub from a mock, we typically only mimic the methods we are actually testing. This is quite useful during

More often than not a stub is created at the beginning of the test suites and made accessible to the suite’s tests. A good practice is to limit the modifications to the stubs to make sure you are always testing the same thing.

If you must make changes it is a good idea to make a local copy to isolates your modifications to a specific test.

Test Stub Examples

HeaderComponent

Below is an abridged version of the component code we are unit testing. The important thing to note: at the end of this method’s execution we make a call to the router service to navigate the user to the “login” route and we need to make sure this and only this method is executed.

/**
 * Simple component providing a navigation header.
 */
...
export class HeaderComponent implements OnInit {
    ...
    /**
     * clickLogout clears the user's creds but also 
     * takes the user to the Login route
     */
    clickLogout() {
        ...
        this.router.navigate(['/login']);
    }
    ...
}

Test Suite Code

Here is the abridged test suite where we create our test stub

...

/** 
 * beforeEach setup executes before each test suite test runs.
 *
 * This allows us to setup the stub before each test
 */
beforeEach(async(() => {

    ...
    
    TestBed.configureTestingModule({
        ...
        providers: [

        /**
         * Create a very basic stub object with one method:'navigate'
         *
         * Use Jasmine's createSpy to create a very basic function
         * which also allows us to "listen in" when it's called
         */
        {
            provide: Router,
            useClass: class { 
                navigate = jasmine.createSpy("navigate"); 
            }
        }
        ...
    ]})
    .compileComponents();

    ...

}));

/**
 * Here we test the method and make sure we actually navigate
 */
it('should navigate to /login when clickLogout is fired', () => {
   ...
   let router = fixture.debugElement.injector.get(Router);
   component.clickLogout();

   // "listen" to make sure that the navigate method has been 
   // called and it was called with the expected value
   expect(router.navigate).toHaveBeenCalledWith(["/login"]);
   ...
});

 

Mocks

A Mock object is a simulated object instance used to mimic a classes behavior using the same interface. In simpler terms, this is a fake class with the same method signature as the Real Thing.

A mock object can be composed of multiple objects (and sometimes multiple mock objects), but most often should be created as simply as possible to keep your tests easily maintained.

Mock Object Example

/**
 * Create a mock of an existing service
 * by simply extending it and overriding some 
 * of the methods you wish to use in your tests
 */
class MockAuthService extends AuthService {

    /**
     * This method is implemented in the AuthService
     * we extend, but we overload it to make sure we
     * return a value we wish to test against
     */
    isLoggedIn() {
        return false;
    }
}

...

beforeEach(async(() => {

    ...

    TestBed.configureTestingModule({

        ...

        providers: [

        /**
         * Inject our mocked service in place of AuthService
         */
        {
            provide: AuthService,
            useClass: MockAuthService
        },

        ...

    ]})
    .compileComponents();

    ...

}));


it('should navigate to /login when clickLogout is fired', () => {

   /**
    * Get the mocked service here from our fixture
    * and add a spyOn over-ride to pretend we have
    * a logged in user.
    */
   let service = fixture.debugElement.injector.get(AuthService);
   spyOn(service, 'isLoggedIn').and.returnValue(true);
   
});

Conclusion

Unit tests are only as good as the environment you can provide for your code under tests. It’s very important to be able to mimic and recreate the environment under which you have both positive and negative results for your code.

Unit Testing AngularJS Components & Services

Unit testing is a very important part of software development, and it is extremely important to Angular applications as they become increasingly more complex. We’ll explain how to set up your unit tests and describe what you can actually test with some examples.

Intro

Unit testing is a very important part of the software development process, especially as your applications become more and more complex. Making sure your code is robust and adaptable is an important aspect of being professional. This is no less true with your AngularJS application.

If you are reading this, you are most likely already sold on unit testing but here’s some benefits and reasons for writing and maintaining your unit tests:

  • The ability to quickly update your code and make sure you are able to regressively test your code.
  • Updating your unit tests to cover a fixed bug will prevent the bug from getting re-introduced!
  • Use a CI to make sure EVERYONE on your team is testing the code.

Angular CLI, Jasmine & KarmaJS

Here at Arroyo Labs we use the latest version of Angular CLI a lot. It’s a great way to start a project very quickly provides a great start for your application. It also gives you some boilerplate unit tests for each component and service you create using the CLI.

While we have explained Jasmine and KarmaJS in past blog articles, here is a quick overview explaining how these frameworks work together:

  • Jasmine
    • A very popular behavior driven Javascript testing framework with a very clean syntax.
  • KarmaJS
    • A framework that allows you to run your Jasmine tests on a device or headless browser. The test runner itself will provide a DOM with which your code is rendered and provides the API that Jasmine will interact with.

Setting up your tests

To create a unit test, you need to include a consistent environment in which to run your code under test and we need to control the required classes and variables that go into creating this environment. Thanks to the magic of dependency injection, we can mock up some classes used by our classes and code.

Let’s take a look at the ‘top’ portion of a unit test we use in our user-admin project (you can find the whole unit test in our repo):

/**
 * Import some basic testing classes and utilities from AngularJS's
 * core testing code. This is the minimum required code to create 
 * a basic unit test.
 */
import {
     async,
     getTestBed,
     TestBed
} from '@angular/core/testing';

/**
 * Import some specific test classes used to mock the 
 * http backend and connection classes
 */
import {
    MockBackend,
    MockConnection
} from '@angular/http/testing';

/**
 * Import the HTTP classes we use in our service
 */
import {
    BaseRequestOptions,
    Http,
    Response,
    ResponseOptions,
    XHRBackend
} from '@angular/http';

/**
 * Finally, we import the required custom classes we use in our service,
 * and the service we are testing as well.
 */
import { User }         from '../shared/models/user.model';
import { AuthService }  from './auth.service';

import { UsersService } from './users.service';

What should we test in a service?

To test a service, we have to understand the underlying concept they represent: isolating logic and code into a re-usable class. This means we have a class we can pass around in our application where we get and manipulate data in expected ways.

Keep in mind, we can really only test publically scoped variables and functions. The unit test itself is really only able to interact with your service in the same way that an application is able to.

So, we have these things to test:

  • What public variables get initialized when we create the service?
  • Do public variables update as we expect when we call public functions?

Example Service Unit Test: UserService

In our UserAdmin project, we have a service called UserService used to interact with and manipulate user data we get from the AJAX backend.

The service itself only has quite a few public methods (it’s a very important class!) so we will focus on just two of the suite’s tests of the same method `getUsers`:

getUsers should return an empty observable list when the ajax request is unsuccessful

This is a test to make sure we return an empty list of users if the AJAX response does not contain an encoded list of users. This is a negative test, we are making sure that we return an expected response even when the backend returns an error.

it('#getUsers should return an empty observable list when the ajax   request is unsuccessful', () => {

 // set up the mocked service to return an
 // unsuccessful response (no users, 500 status)
 // with a helper method
 usersBodyData.success = false;
 setupConnections(backend, {
     body: {
         body: usersBodyData // use the previously init'd var for consistent responses
     },
     status: 500
 });

 // set up our subscriptions to test results 
 // when we actually get a result returned
 service.users$.subscribe((res) => {
     if(res) {
         expect(res).toBeTruthy();
         expect(res.length).toEqual(0);
     }
 });

 service.total$.subscribe((res) => {
     if(res) {
         expect(res).toBeTruthy();
         expect(res).toEqual(0);
     }
 });

 // make the actual request!
 let res = service.getUsers();

});

getUsers should return an observable list of users and result total when the ajax request is successful

This test makes sure that we get an observable list of users if the AJAX response is successful. To make sure this happens, we mock the response as though we have a JSON encoded list of users.

it('#getUsers should return an observable list of users and result total when the ajax request is successful', () => {
 // set up the mocked service to return an
 // unsuccessful response (users, 200 status)
 // with a helper method
 setupConnections(backend, {
 body: {
 body: usersBodyData
 },
 status: 200
 });
 
 // set up our subscriptions to test results 
 // when we actually get a result returned
 service.users$.subscribe((res) => {
 if(res) {
 expect(res).toBeTruthy();
 expect(res.length).toEqual(2);
 }
 });
 
 service.total$.subscribe((res) => {
 if(res) {
 expect(res).toBeTruthy();
 expect(res).toEqual(2);
 }
 });
 
 // make the actual request, with some params to pass via query string
 // we will explore this in a future post
 let res = service.getUsers(42, 42, 'id', 'desc');
});

What should we test in a component?

A component, like a service, is also a re-usable piece of code but it also has a defined lifecycle from its parent class and a frontend element via it’s template and optional CSS.

So, here is what we have to test:

  • Does this component actually get constructed?
  • What public variables get initialized and what DOM elements get rendered when we create the component?
  • Do public variables update as we expect when we call public functions?

Like we have noted above when discussing testing a service, you can really only test things that have been scoped as public by the component itself. This does include rendered DOM elements and you should test that these elements appear and render as expected since these are made public by the component itself.

Example Component Unit Test: UserListComponent

Test that the component actually results in a rendered component

it('should create', () => {
   fixture.detectChanges();
   const compiled = fixture.debugElement.nativeElement;
   component.ngOnInit();
 
   component.users = [];
   component.total = 0;
 
   // do we have a component at all?
   expect(component).toBeTruthy();
 
   // create new user button
   expect(compiled.querySelector('.btn-info')).toBeTruthy();
 
   // do we have a table
   expect(compiled.querySelector('table')).toBeTruthy();
   expect(compiled.querySelectorAll('tr').length).toBe(2);
});

Test that we display a list of users with a mocked response

it('should display list of users', () => {
   fixture.detectChanges();
   const compiled = fixture.debugElement.nativeElement;
 
   setupConnections(backend, {
       body: {
           body: bodyData
       },
       status: 200
   });
 
   component.ngOnInit();
 
   // create new user button
   expect(compiled.querySelector('.btn-info')).toBeTruthy();
 
   fixture.detectChanges();
 
   // do we have a table with users?
   fixture.detectChanges();
   expect(compiled.querySelectorAll('tr').length).toBe(21);
 
   // do we see the expected page count
   expect(component.getPageCount()).toBe(2); 
});

Conclusion

Unit testing is a not a oft-celebrated portion of the software development cycle, but it is an important part of the process. Once you have good tests in place, you can pivot direction and update your code with an increased sense of security.

Angular 2 VideoJS Component

Using components is a fantastic way to include 3rd party libraries like VideoJS in your Angular 2 application.

We have talked previously about the basics and different types of Angular 2 components, but today we will give you a practical example of using Angular components to wrap an external library. We will focus on the excellent video media player library VideoJS, but this can really be applied to many other libraries as well.

Using external libraries in Angular 2

To actually use some 3rd party libraries within an Angular 2 application, you need to jump through some hoops. Most libraries require direct access to the DOM model and expect full control of the DOM rendering cycle. Part of the magic of Angular 2 is ceding some of that control to allow it to render when it feels like it.

To get around this hurdle you simply need to wrap your 3rd party libs in a way that gives more control to Angular and allows the 3rd party library access to the DOM via the application lifecycle.

Most 3rd party libraries, like VideoJS, would have been wrapped in a directive in previous versions of Angular. In our example we will use a component, but it is possible to use a pipe or a service depending on your 3rd party library.

VideoJS

VideoJS is a (rightfully) popular media player library that makes it easy to skin and control media files. This library can handle many types of media files like MP4s, MOVs and even YT (with a plugin).

Videos have traditionally been a tough element to render consistently across browsers. Given the rather recent support for the HTML 5 video element things have gotten better, but it has always been a little tough to consistently style the player itself. VideoJS both abstracts out the skin and API hooks which make things much easier than in the past.

One of the reasons we chose this library for our example is that it’s pretty self contained. It does not require external libraries like jQuery and is also relatively small.

VideoJS Component

Check out this plnkr to see the example VideoJS component.

First things first: include the VideoJS library assets in the application HTML head so we can use it with our component.

<link href="https://vjs.zencdn.net/5.11/video-js.min.css" rel="stylesheet">
<script src="https://vjs.zencdn.net/5.11/video.min.js"></script>

Our example component is pretty simple, lets take a look at some of the component code itself:

The template code

  <video *ngIf="url" id="video_{{idx}}"
     class="video-js vjs-default-skin vjs-big-play-centered vjs-16-9"
     controls preload="auto"  width="640" height="264">
     
    <source [src]="url" type="video/mp4" />
   
  </video>

This is a pretty simple template, and really only consists of a video element with some CSS classes and a source element.

Some things to note in the template code itself:

Prevent rendering the element itself unless we have a video URL:

*ngIf="url"

Add a unique index to make sure we can reference this element alone:

id="video_{{idx}}"

Add a `source` element for the video url itself:

<source [src]="url" type="video/mp4" />

Initialize the Player in ngAfterViewInit

We need to wait until the component template is rendered before we can let VideoJS do it’s magic. In order to let Angular tell us when the component’s lifecycle has reached that point we use a specific event hook called ngAfterViewInit that fires when the component template has been been completed.

Check out the code below to see this in action:

  ngAfterViewInit() {
    
    // ID with which to access the template's video element
    let el = 'video_' + this.idx;
    
    // setup the player via the unique element ID
    this.player = videojs(document.getElementById(el), {}, function() {
      
      // Store the video object
      var myPlayer = this, id = myPlayer.id();
      
      // Make up an aspect ratio
      var aspectRatio = 264/640;
      
      // internal method to handle a window resize event to adjust the video player
      function resizeVideoJS(){
        var width = document.getElementById(id).parentElement.offsetWidth;
        myPlayer.width(width).height( width * aspectRatio );
      }
      
      // Initialize resizeVideoJS()
      resizeVideoJS();
      
      // Then on resize call resizeVideoJS()
      window.onresize = resizeVideoJS;
    });
  }

Component Element

Include the VideoJS component in your component:

<videojs [idx]="idx" [url]="video"></videojs>

If you check out our plnkr you can see this on the app.ts you can see we support multiple video elements as well.

Conclusion

Components are a great way to help separate your coding concerns, and are a major building block in creating an Angular 2 application. They are also great to encapsulate and add some sanity to 3rd party libraries that you wish to use in your projects!

If you have any comments concerns or questions, please let us know in the comments!

Introducing the Erdiko User Admin

Introducing the Erdiko User Admin Package! A user administration package built with an Erdiko powered backend and a Angular 2 frontend.

We’re excited to introduce the Erdiko User Admin! A modular package that provides an attractive UX to allow you to manage your users.

This is still very much a work in progress, but since we’re so excited, we want to let everyone know about this project (and request some help to keep us moving).

Check out our User Admin Project at this Github Repository and our Packagist entry.

Project Features

We wanted to create a modular and simple User Admin you can ‘bolt-on’ a new or existing project. We keep this as lean and mean as we could, but still providing some cool stuff to help get you started.

While this package is still very much in development, it does provide some of the following features:

  • A sortable and paginated list of user records.
  • An attractive user interface allowing the user to create, edit & delete user records
  • JWT user authentication!

Here’s some screenshots of our UX:

Installation and Setup

The User Admin package is a part of the Erdiko module ecosystem. Installable and upgradable via Composer. This makes it very simple to start a new project via this simple command.

composer create erdiko/user-admin [PROJECT NAME]

Please note that as of this time, we have not created an official release. You will need to include the minimum stability flag when you create your project:

composer create erdiko/user-admin [PROJECT NAME] --stability DEV

Package Dependencies

Here’s a brief list (and a bit of a plug) of some of the other Erdiko Packages we as a team have been developing that we use to build this project. While we use these packages for our development, we have planned to make these as modular and replaceable as we can.

Here’s the list:

  • erdiko/core
    • The base package that provides our basic routing and templating.
  • erdiko/authenticate
    • Authenticate the user’s credentials to assert they are who they say they are.
  • erdiko/authorize
    • A package that helps us enforce some user roles.
  • erdiko/users
    • Our Erdiko package that provides the backend storage and basic routes we use to interact with these models.

AngularJS 2

We utilize the great Angular CLI project to start and maintain the Angular code itself. This project was a great boon to help us get started on a well structured and maintainable Angular application.

The internal structure is “just” a simple app, but we have updated the NPM script to compile and move the resulting files to an directory accessible to the Erdiko application Home route.

NPM Run Scripts

Here is a quick list and an explanation of some of the custom NPM run commands we have for this project.

  • Start the local Angular Development server: npm run start
  • Run the unit tests: npm run test
  • Run the e2e/functional tests: npm run e2e
  • Compile and export files for end user: npm run build

Next Steps

Here’s an incomplete list of some of the next things we plan on working on, and completing, with the project in the future:

  • Jasmine Unit Tests to cover our angular code
  • KarmaJS Functional Tests to cover the entire application end-to-end
  • A basic User facing profile designed for user extension

How to Contribute

If you have an idea for a new feature, have an idea on how to improve a feature, or (gasp) you have found a bug please report this on our Github Repo Issues page.

However if you are just excited about this project, feel free to “star” this repo on Github to show your support.

We would also love to know if and how you use this module in your own projects!

To set your environment up for local development, please follow these steps:

  1. Clone your fork of the User Admin project into a local directory
  2. Clone the following packages into the same directory
  3. Copy the composer-dev.json file to composer.json
  4. Start your docker container docker-composer up --build

Conclusion

Thanks for reading about our exciting new package! Feel free to leave a comment or ask questions below, or feel free to comment on our Github Repo page!

Angular 2 Animations

Animations are a very important part of User Experience design for web applications. We’ll will explore how animations are created and configured in Angular 2 and provide some concrete examples.

Introduction

Continuing on our series of Angular 2, we’re now going to explore  animations in Angular 2. Clearly smooth animation and transitions are an important part of the UX design for interactive applications.

Let’s start off by talking about how we animated things in Angular 1.x.

Animations in Angular 1

Angular 1.x allowed for animations between states for a handful of directives and elements, which when coupled with the nature of an Angular application, presented some great results. Two methods were provided to allow the user to add these transition states: CSS and Javascript. While both methods had some pros and cons, it also led to different interfaces that could easily confuse a developer.

CSS transitions were provided simply by using CSS3 transitions, which have the benefit of not requiring additional JS libraries and are as fast as your browser can render. Most of the control of this style of animation is controlled by using a unique class name structure and Angular handles a class change based upon a unique naming scheme.

The ngAnimate module provided a Javascript interface to control animations. This module allowed the user to use (most likely) jQuery’s animation controls or a 3rd party JS lib to render animations. This has some benefits of allowing some fine grain control, but you were also limited to what the 3rd party library allowed you.

Animations in Angular 2

Angular 2 uses the Web Animations API to really let your browser control animations with the highest possible performance and timing control.

Unlike Angular 1.x’s interface, the entire animation library is contained within a single module. This allows for a common simple interface, but since it uses the Web Animation API, also allows the browser to optimize the animation control to a finer control that previously allowed by CSS3 only animations.

While I should note that this also requires a compatible browser to run these animations, there is a polyfill available to cover legacy browsers that is easily installed.

Let’s explore some of the basic concepts used for defining and controlling Angular 2 animations.

Triggers

Triggers are the term for a function that defines the states and transitions used for an animation. These are defined in the component annotation metadata fields and have a corresponding placement on a component’s template to indicate where an animation is applied when the end user interacts with the application.

Here’s an example of triggers defined in a simple component, and explains where we put the settings we explain later in this post:

animations: [
  trigger(
    'pState', 
    [
      state('inactive', style({
        transform: 'scale(.9)'
      })),
      state('active', style({
        fontWeight: "bold",
        transform: 'scale(1)'
      })),
      transition('active => inactive', animate('50ms ease-out')),
      transition('inactive => active', animate('50ms ease-in'))
    ]
  )
]

States

States are a defined condition, or a specific point in time by, that you can define in your Angular 2 component via a string. These finite conditions allows you to define a value you can pass into your components template to help set up your animation conditions. Examples of these states are “active” and “inactive” that can identify an element that is “On”. See our first example for a demonstration of these states.

Timing

Timing in Angular 2 is defined by three properties: duration, delay and easing

Duration controls how long an animation runs. Defined by a string or an integer in milliseconds or seconds, it’s never been easier to define the length of time a transition occurs. Here’s an example of a duration of two seconds “2s” and 200 milliseconds “200ms”.

Delay, much like you assume, is about the time that elapses between the trigger execution an the start of the animation. You can even define the delay in the same line you define the duration in this example where it last two seconds after a delay of 3 seconds: “2s 3s”

Easing is how angular controls the animation accelerates and decelerates during it’s runtime and is a pretty succinct way to add some ‘realism’ to your animation. Identified by a string, these have the same common names as the control parameter in CSS3. Some more information can be found here on this site, easings.net.

Callbacks

Callbacks are just methods called when an animation starts and stops. This is useful for executing code based on an animation’s timing, and if you have ever tried to chain commands together using browser timing alone, you will seriously jump for joy.

Here’s an example from the official angular guide with the callback methods “animationStarted” & “animationDone”:

...
  <li>
    (@flyInOut.start)="animationStarted($event)"
    (@flyInOut.done)="animationDone($event)"
    [@flyInOut]="'in'" >
    {{hero.name}}
  </li>
...

 

Example 1: P Tag State on Button Click

Our first example shows hows we can animate the two states (Active & Inactive) of a displayed P tag. Keeping this simple, we illustrate how to set up a component to use the animation library and how to set up two simple states and their transitions.

Click the gif of the plnkr below to see the code in an active plnkr:

ex_1-p_tag

Example 2: Multi-Step Animation with Callbacks

Our second example shows a multistep animation that uses keyframes to add multiple steps to a transition, and callbacks that output the start and end of each animation to the console.

Check out this plnkr, and open your console, to see this in action:

ex_2-multi-step

Conclusion

Animations add so much to web applications that it’s a mistake not to include them. Thankfully Angular 2 makes this easier to include and trigger your animations with minimal work from the developer.

Angular 2 Attribute Directives

Attribute Directives are a powerful way to affect the appearance or behavior of a DOM Element in your Angular 2 Application. We examine how attribute directives work, and how you can build re-usable custom code for your projects.

Introduction

AngularJS really introduced the concept of organizing and extending the DOM for use in real web applications. AngularJS 1.x brought us the idea of a Directive, or a way to indicate that a DOM element was “special” and will have a behaviors or an appearance that will be controlled by your code. AngularJS 2 took this idea and ran with it, but this also means we need to explain some stuff. We now have 3 tools at our disposal for interacting with the DOM: Components, Structural Directives and Attribute Directives.

Components, which you should have at least read about by now, are the most basic of the angular building blocks. Everything is a component and all components have directives; components are created from one or more directives. Directives are the method to identify a component’s behavior or associate a variable to a component.

Structural Directives are used to add or remove elements from the DOM. Common examples are *ngIf or *ngFor. These directives allows you manipulate a component based on a variable value or allow a component to iterate a series of values.

Finally, we have Attribute Directives. Attribute directives allow you to attach a behavior to an element or affect it’s appearance and re-use this throughout your application or package it up as something you use in all your projects.

Using Attribute Directives you can create a stylized DIV tag that formats all text and adds an event listener to change the color when the user mouses over the text. Show off your example code with some syntax highlighting!

I should also note that Attribute Directives can access and manipulate application values, but primarily are focused on affecting the component they have been attached. Think of this as more like CSS Selector Class on steroids. Make sure you do the “real math” of your application in your components.

Anatomy of an Attribute Directive & How to use it

Attribute Directives can be simple or complex. The simplest example of an Attribute Directive could be a simple CSS property attached to a P Tag:

<p [style.background]="'red'">I'm red!</p>

Anything more complex than the above example requires a little more wiring. Let’s look at an commented example from the official docs called “Highlight”:

// Import some stuff from the core library
import { Directive, ElementRef, Input, Renderer } from '@angular/core';

// create a Directive to decorate. To prevent confusion let's call this myHighlight to 
// illustrate the fact this this is a custom appearance
@Directive({ selector: '[myHighlight]' })

export class HighlightDirective {

    /* 
    This is a pretty simple example, we just need a constructor. Pass the element we wish to affect in as "el" and make sure we interact with the DOM renderer with the obvious name of "renderer"
    */
    constructor(el: ElementRef, renderer: Renderer) {

       /* 
       Set the element's Background Color CSS property to Yellow, as though we "highlighted" it with a marker.

       Note we reference the element itself as el.nativeElement so we actually update the rendered DOM model itself.
       */
       renderer.setElementStyle(el.nativeElement, 'backgroundColor', 'yellow');
    }

}

Use and apply your custom directive attribute in your application
<p myHighlight>Highlight me!</p>

Some Attribute Directive Examples

Italic & Underline

A very simple example showing how we can make something italic, and underlined, using a simple attribute directive.

@Directive({ selector: '[alItalic]' })

export class ItalicDirective {
 
  constructor(el: ElementRef, renderer: Renderer) {
    renderer.setElementStyle(el.nativeElement, 'fontStyle', 'italic');
    renderer.setElementStyle(el.nativeElement, 'textDecoration', 'underline');
  }
 
}

Plnkr

Blink

We can also bring back the much missed BLINK tag using an attribute directive. This example illustrates how we can actually encapsulate some logic and manipulate the DOM element’s CSS with this logic by using an attribute directive that can be placed on any block element.

@Directive({ selector: '[alBlink]' })

export class BlinkDirective {
  
    constructor(el: ElementRef, renderer: Renderer) {
      setInterval(() => { 
        let style = "hidden";
        if(el.nativeElement.style.visibility && el.nativeElement.style.visibility == "hidden") {
          style = "visible";
        }
        renderer.setElementStyle(el.nativeElement, 'visibility', style); 
      }, 750);
    }
    
}

Plnkr

Detected User Event – Click

Finally, here’s an example where we can listen for a user event (click) on an element by simply using an attribute directive.

import { Directive, ElementRef, Input, Renderer, HostListener } from '@angular/core';

@Directive({ selector: '[alClick]' })

export class ClickDirective {
  
  private _el: ElementRef;
  
  constructor(el: ElementRef, renderer: Renderer) { 
    this._el = el;
  }

  @HostListener('click') onClick() {
    let str = this._el.nativeElement.innerHTML;
    alert("innerHTML from the element you clicked: " + str);
  }
    
}

Plnkr

Conclusion

We really only scratched the surface of what you can do with Attribute Directives. AngularJS has always been a framework that allowed you to organize and extend your DOM based applications, but AngularJS 2 has taken this to a whole new level.

Hope you enjoyed this post!

Angular 2 Pipes

Angular 2 pipes replaced filters as a method to format and manipulate text for output. We explore some background behind pipes and provide some simple examples to explain these concepts.

Introduction

Pipes are a feature of Angular 2 that allows you to contextually manipulate and format text on the front end. From simple date formatting, to a complete transformation, pipes allow you to separate how you display data provided from the backend.

Prior to Angular 2, text transformation was provided by “filters”. Conceptually the same in usage, Angular 2 gives us a little more power and flexibility to how we can package up the text manipulation power of these smaller components.

Commonly used & built in Pipe examples

Some pipes merely intake a string and return a formatted result, others take parameters to help construct the resulting output.

The best part of using these are literally built into the framework. No extra file library inclusions are required.

UpperCasePipe & LowerCasePipe

UpperCasePipe & LowerCasePipe are two built in pipes that allow you to transform text, as their names would imply, before outputting to the DOM.

These are the most simple of pipes (and really, could be replace with some CSS) but they illustrate the mechanic: The value you wish to transform goes on the left a “pipe” (this “|” character) and then the transformative function goes on the right.

Here are two quick examples:

<p>{{ firstname | lowercase }}</p> // Foo -> foo 
<p>{{ lastname | uppercase }}</p> // Foo -> FOO 

Pretty simple, and lets us explain some more complex setups.

DatePipe & CurrencyPipe

There are also some slightly more complex built in pipes, some of which take in full objects, other take expressions from which to transform the text they transform.

DatePipe

DatePipe formats and transforms a Date object into a string based on a provided expression and locale rules.

Here are some example DatePipe usages with some of the build in expressions:

<p>{{ now | date }}</p> // Nov 15, 2016 
<p>{{ now | date:'medium' }}</p> // Nov 15, 2016, 12:05:08 PM 
<p>{{ now | date:'M-d-y' }}</p> // 11-15-16

CurrencyPipe

Like the DataPipe, CurrencyPipe also formats using a provided express and based on the browser’s locale. I’ll leave you to check the official documentation, but this is a very basic example.

<p>Total: {{ total | currency:'USD':true:'4.2-2'}}</p> // $10.99

Creating Custom Pipes

Creating custom pipes can be a little scary and intimidating at first, but is not hard in principle. We’ll walk you through the basics and provide a few examples to work from.

Structure and formatting your Pipe definition

Creating a pipe is pretty easy, in fact it looks like how you create an angular component. Let’s break down this example:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'foobar'})
export class FooBarPipe implements PipeTransform {
 
    transform(value: string, args: string[]): any {
        return "FooBar" + value;
    }
 
}

After including the Pipe & PipeTransform libraries from angular/core, you simply need to use the @Pipe decorator. The decorator accepts a parameter called “name” which is used to reference your custom pipe in your template code.

Finally, your pipe must implement a method called “transform” which, coincidentally, transforms your provided text or object.

And including into your app module is also quite simple:

import { FooBarPipe } from './foobar.pipe';

...

@NgModule({
 imports: [ BrowserModule ],
 declarations: [ App, FooBarPipe ],
 bootstrap: [ App ]
})
export class AppModule {}

Parameters

As we noted previously, you can also pass parameters to a pipe to affect the how the value piped in is transformed. You can send multiple parameters as well each separated by a colon (“:”) and extract them in your transform method.

Example 1: Prefix “FooBar” to a provided string

This is a simple example of a custom pipe that prefixes “FooBar”:

Example 2: Multiply a provided integer by Number

Show an example where we multiply the output by 42 (provided by the component) and return a result. This will illustrate the idea of stateful pipes.

Example 3: Convert string to Pig Latin

Here is an example of a pipe that converts a provided string to Pig Latin.

Conclusion

Pipes are a useful and easy to learn concept in angular 2. While it’s easy to think they are limited to formatting and displaying text, we have also shown some re-usable examples where a company can have a small arsenal of pipes at their disposal.

Angular 2 Routing

Angular 2 Routing is bit complicated when compared to routing in Angular 1.x but it is very powerful. We hope to clear up some of the common confusion when setting up routing and provide some practical examples as references.

Understanding routing in you application is the key to creating a single page application. Routing is what allows view navigation in your application like ‘detail views’, end user bookmarking and even allows you to set up a ‘logged in’ version of your applications views.

Routing isn’t included by default in Angular 2, in fact you have to explicitly include it as a library. I also will say, it’s not incredibly intuitive to configure. We’ll take some time to explain the history of the router and dive into some of the basic concepts.

Basic Concepts of Routing in Angular 2

Router Library

The router itself is implemented in the optional Router Module, which is kept separate to keep the base library size low. Include it in your main module like this:

import { RouterModule } from '@angular/router';

...
@NgModule({
 declarations: [ ... ],
 imports: [
     RouterModule.forRoot(routes),
     ...
 ],
 providers: [ ... ],
 entryComponents: [AppComponent],
 bootstrap: [AppComponent]
})
export class AppModule {

}

Base HREF

The base HREF is the starting point for your application and is used to create your home route. It’s this starting point that your browser will also use to create a history to prevent ‘breaking the back button’ which is always a sticking point in SPAs.

Here’s the syntax you need to add to you html:

<base href="/">

Configuration & Routes

const routes = [ 
    // Default, or home, path. This matches your Base HREF
    { 
        path: '', 
        component: HomeComponent 
    }, 

    ...

    // Wildcard, or the 'catch-all' route pattern. If the requested
    // route does not match anything above, this route is displayed.
    { 
        path: '**', 
        component: HomeComponent 
    } 
];

Resolves & Guards

Resolves are services that must be completed before allowing the route to be accessed and loaded. This is how we can ensure that the data is available for the route prior to allowing the user to access the route.

A quick example of this would be a UserResolve class that retrieves a list of users before displaying the route.

Guards are a method to prevent a route from being accessed unless a certain state is met.

A quick example of this would be a LoggedInGuard class that prevents a user from accessing a route unless they are logged in.

Child Routes

Child routes are a way to add specific routes to a feature.

Example 1: A One Route Application

Below is an example of an application with a single route. This illustrates including the router module, a base href and a very basic route configuration.

Example 2: A One Route Application with a Resolve

Below is an example of an application with a single route that requires a service to resolve a data retrieval before rendering.

Example 3: A multiple route application with a child route

Below is an example of an application with two routes and a child route.

Conclusion

While it may take some time to completely wrap your mind around routing in angular it’s clearly an important part of creating a real SPA. Don’t be afraid to take and reference your own notes!

Providing data via Angular 2 Services

Interaction with data in Angular 2, internally and from external sources, is based around the concept of services. Learning more about services is integral to learning how to create an Angular 2 component or application.

Angular 2’s biggest strength is the reliability of encapsulation and re-use, which means passing data to and between components can be a pain at first. You are highly discouraged from getting data from the DOM, making AJAX calls in your components is a no-no. How are you supposed to get data to your things?

This is where you start to use Angular Services. Services are an injectable class that allows you to keep all your functionality in one place. Here’s the official definition of a service in Angular 2 from the docs:

A service is a class with a focused purpose. We often create a service to implement features that are independent from any specific view, provide shared data or logic across components, or encapsulate external interactions.

You have data you need from an AJAX endpoint? Create a service.

You want to maintain state for an object that multiple components? Create a service.

Want to do anything cool with some data across your application? Create a service.

For those of you familiar with the pattern, Services in Angular 2 are really Singleton Service models. Its a single instance you pass around. It has a state, it has some methods. Its easily mocked and you know where the ‘meat’ of your application is at all times. It allows you to move the data manipulation out of the display code entirely.

Coming from a Vanilla JS background all of this may seem a little over complicated. While simplicity is something to strive for, there are good reasons for this level of abstraction:

  • Encapsulating the functionality of your services is a good practice
  • You can focus on functionality in your components with a well defined service
  • Mocking a service is easier than mocking an environment

Here’s some examples of services in action:

Example 1: A Simple String Returning Service

This is an example of a simple data service providing some data to a component. While extremely simple, it shows how to get data ‘into’ a component from an outside source:

The component itself relies on the service to provide the data to the front end. The value of ‘bar’, displayed in the component’s template actually comes from the service itself. When the component loads, it calls the “getBar” method of the service which returns a simple string.

While this example might seem very trivial, it lays some groundwork for the other examples. A service provides data external from the component in an ‘agreed’ upon way. This contract allows us to take some control of how we get the data away from the component, which should really just focus on how the data should be displayed.

Example 2: A service that allows us to share data between more than one component

This is an example of a service that allows a total of three components to interact together.

If you look at the code in the example, this small ‘app’ has three components that each include the CounterService. This extremely simple service allows us to interact with a single integer variable that can be incremented and decremented via two completely separate component’s buttons.

Again, while maintaining a ‘contract’ we can allow each one of these components to focus on the display and events rather than the actual manipulation of the data.

Example 3: A service that provides data from an AJAX (external) source

This is an example of an AJAX service providing data to a component. A ‘locally’ hosted JSON file is retrieved via AJAX in the service itself and then sent to the component. This component is able to interact with the data entirely through the service itself. This level of abstraction allows the component to strictly focus on the display and styling of the data provided by the service.

 

Promises vs Observables in your AJAX services

Promises are great and a well trod subject, I’ll leave it up to you to read more about their benefits (or you can revisit my previous blog post: http://blog.arroyolabs.com/2016/04/angularjs-2-ajax/). Observables, when compared to promises, allow you to specify not only when something is ‘done’ but when something has changed.

This most definitely comes in handy when you create a service like the example above that allows you to detect when any changes occur from your service.

A Final Note

While the final architecture of your application or bundled component is really a choice you need to make, I hope we were able to clear up some of the basics of using services in Angular 2.

 

End to End testing your Vanilla JS App with Protractor

ProtractorJS is a robust and easy to use e2e test framework specifically designed for testing AngularJS applications. With some simple edits and a slight change in thinking, you can also use it to test your non-angular web apps and provide some sanity to your testing strategy across projects.

ProtactorJS is an end to end test framework from Google used to test AngularJS Apps. While similar to existing tools like CasperJS, ProtractorJS is specifically designed for use with AngularJS.
With minimal effort you can use Protractor with your Vanilla JS web app as well. Why would you do this?
For one, using the same test framework for all you apps provides some sanity to writing tests for all of your projects. And you can’t honestly tell me you have all your apps converted to AngularJS already.
Second, it’s gaining popularity and for good reason. It’s a solid testing framework and is relatively easy to set up. Also, it has the backing of a very well known company (cough cough, Google) so it will be around for a long time.
Finally, it’s use of Jasmine and suite structures allow you to write some flexible tests. Encapsulate your logic, group stuff in ways that make sense. No more fragile tests!
Enough stumping, let’s get to the parts you actually care about.

Installation and Set Up

While I’ll point you at the official docs for installation instructions, I’ll provide the basic elements required to installing and running your Protractor tests:
  1. Protractor, Karma & Jasmine
    • Clearly, you need to install Protractor
    • Protractor uses Karma to connect to Selenium
    • Jasmine is used as the testing syntax.
      • You can use other frameworks, but my preference is Jasmine.
  2. Selenium Server & Webdriver
    • Protractor interacts with your tests using Seleniums Server and Webdriver. You can run Selenium locally or use a hosted service like Sauce Labs.
    • Local installation and setup is turn key simple using NPM.
  3. A Web server
    • Since your tests use a real browser to execute, you need a host of some kind.
    • It’s entirely possible to run your tests against an external server (like your staging server), but in practice I like to serve locally. In our example I used the local-web-server NPM package.

Protractor Test Concepts

Again, I’ll point you to the main documentation for longer descriptions of the concepts, I wanted to point out some that need to be discussed when prepping your protractor tests for execution on your VanillaJS app.

Config File

A config file sets up some required variables and tells Protractor how to run its tests. This includes a directory where your tests are held, the testing framework you use to write your tests and the address to the selenium server instance you use to run Karma.

Spec File (Test Suite) – “Describe”

Test suites are groups of testing conditions that focus on a particular section or part of your application. Using Jasmine, these are structure with the “describe” function and a brief string indicating the portion of the application under test.

Test Hooks

Hooks are small functions that are called during test executions. An example is the beforeEach hook we use to set up our tests for use with non-angular code. See the note below on exactly what goes in this hook.

Test Blocks – “It”

Test blocks are identified by an “it” phrase that describes in simple terms what you expect to happen. This is useful for turning user stories into tests like “User Registration Form should validate user input”.
These test blocks do have some minimal setup but are mostly for performing actions and asserting values. Check out our example code to see some of this in action.

Page Objects

Page Objects are similar to test fixtures in other testing frameworks, but thats underselling the usefulness of this concept. Page Objects are small JS objects where you can encapsulate and abstract out common page elements and share between your tests.
Use these to abstract out some commonly tested things, like getting the text or value from a page element. If you use your page object in all your tests, you only have one place to update when a change is made (instead of having to update ALL your test suites).

Running Protractor on your Vanilla JS App

Like we noted above, Protractor was designed for testing AngularJS apps by default. A large difficulty in e2e web app testing is knowing when something has rendered on the page and is ready to have some interaction. AngularJS abstracts how you work with the DOM in JS as well as having some control over how something is determined to be “ready” using Zones.js.
Three major things need to be done to make sure your Protractor test will actually work with out Angular:
  • Expose the web driver in a way you can access the DOM for interaction.
    • Due to the nature of how Angular abstracts the DOM and how it takes over all the app’s event cycles. We need to expose the Selenium Web Driver in a way you won’t hate.
    • Add this line to your onPrepare hook in the config file to assign the web driver to an global variable called “dv”
      • global.dv = browser.driver;
  • Tell the test not to wait for Angular to give the “go ahead, I’m ready” signal.
    • Protractor uses Angular to tell it when the page under test is ready to be tested. We need to skip this in order to test our non-angular app.
    • Add this to each test suite’s beforeEach hook to make sure the test knows to run as we expect
      • dv.ignoreSynchronization = true;
  • Start thinking about your tests with Promises
    • While I’m sure most of us at this point have seen and used Promise style functions. When testing an Angular app, using the default locators is easy. Since we are testing our app using the native web driver, we need to use a promise to allow Selenium to return the DOM element itself. Really though, it’s not that tough.
    • Here is an example where we want to assert the value of an element with the css ID of “foo” using a series of chained promises.
expect(dv.findElement(by.id('foo')).getText()).toEqual(“Bar”);

Plugin – Protractor Utils

Protractor does indeed have a very basic plugin system that gives end users some ways to extend base functionality. I’m still trying to understand this system myself (I haven’t figured out how to use a plugin that isn’t globally installed) I have found one that is very useful called jasmine2-protractor-utils.
I’ll leave some of the longer explanation of this plugin to the author, but my favorite feature is the ability to take a screenshot of the browser in the test on suite or block failure. Once you get things up and running so your tests are running automatically, having some visual artifacts of a failed test will help you replicate and diagnose what and how things went wrong.

Example – Movie Vote

Here is an example (very small) Web App demonstrating a very basic suite of Protractor tests. You can simply clone this repo, install the required packages using the package.json file and run these tests. Simply follow the instructions in the README.md file.
https://github.com/arroyolabs-blog/movie-vote-protractor
For an example of an intentionally failing test, check out the `mv-home-fail.spec.js` test in the tests directory.