Working with Vanilla JS in Web Applications

Why use Vanilla JS instead of any number of the frameworks available or even TypeScript? The answer is largely irrelevant if a choice has already been made. However, deciding to replace JavaScript with some alternative for all use cases is an absolutism missing the mark. This article will describe the use of Vanilla JS leaving the choice of what language to use up to you.

Class Definitions & Namespaces

ES6 classes are not yet fully supported in the browser. Many of the limitations mentioned in this article are most relevant when developing with ES5 – such as developing for Internet Explorer or other antiquated browsers. Even without full support of classes, a similar effect can be achieved in JavaScript and it is actually quite easy to do!

We first want to make sure that the class definition is contained. This means it should not pollute the global namespace with methods and variables. This can be accomplished by using a closure – a specific one called an IIFE.

(function (global) {
  "use strict";

  global.API = new MyObject();

  function MyObject() {
    var self = this;

    ... var privateVariable ...

    ... function privateMethod() ...

    ... self.publicMethod ...
  }
})((1,eval)('this'));

Notice that the global namespace is passed to the IIFE – since they are just methods, they can be used as such! If you want to know more about how the global namespace is obtained, check out this enlightening StackOverflow post: (1,eval)(‘this’) vs eval(‘this’) in JavaScript?

“Use Strict”

"use strict"; //seriously, do it.

The class can be initialized and stored at global scope such as inside a single app-specific namespace:

(function (global,app,http) {
  "use strict";
  global[app] = global[app] || {};
  global[app][http] = new Http();
  // global.App.http.publicMethods()

  function Http() {
     var self = this;
     // var privateVariables ...

     // self.publicMethods = function ...

     // function privateFunctions() ...
  }
})((1,eval)('this'),'App','http');

I find it easier to write client-side JavaScript as an API. Leveraging the design patterns this encourages offers many benefits to code quality and maintenance. In the code above, an instance of Http is assigned to the http property in the global.App namespace. Certainly, this should contain our methods for making HTTP calls! Code organization is one of the best things about approaching the application’s client-side JavaScript in this way. Usually, the constructor function, not an instance, would be stored – which allows certain SOLID principles to be applied.

The Constructor Function

The Http function is a special kind – a constructor function. This means an instance can be created using the new operator with the constructor function call.

function MyObject() {
}

var instance = new MyObject();

This should look familiar if you have ever created an instance in Object-Oriented code before.

Capturing this

The fact this isn’t always the same is both the power and the curse of JavaScript. The first line of the Http constructor function is capturing this in a specific context to help overcome the curse, and leverage the power:

function Http() {
  var self = this;

  ...
}

At the scope of the constructor function, this refers to the Http object. A private variable is declared and initialized to capture it and make it available to all public and private members of Http – no matter what this happens to be during the invocation of those members. Capturing this only once and at the scope of the corresponding constructor function will reduce the possibility of this fulfilling its curse!

private Members

The variables and functions created at the scope of the Http constructor function will be available to all public and private members within the Http object.

function Http() {
  var self = this,
      eventHandlers = {};

  function addEventHandler(event, handler) { }
  function removeEventHandler(event, handler) { }
}

In this case, self, eventHandlers, and the add/remove event handler functions are private members of Http. They are not accessible to external sources – only public and private members of Http can access Http‘s private members.

public Members

The properties and methods exposed on the Http object, such as those existing in the prototype chain, that can be accessed from external sources, are considered public.

function Http() {
  var self = this;

  self.get = function (request) { ...
  self.post = function (request, data) { ...
}

Add public members to the self variable within the constructor function. This allows other code to perform the operations of an Http instance.

static Members

Members can be static as well. By declaring a variable on the constructor function itself, it can be assigned a value, instance, or function that is public while not depending on an instance to be created using the constructor function:

function Http() {
}

Http.setup = function () { ...

The static Http member can be used without creating an Http instance:

// ... application code doesn't create an Http instance
Http.setup();
// ... application code doesn't create an Http instance

The member is public and available anywhere the Http constructor function is available.

Execution Contexts

Without going into the depths of execution contexts in JavaScript, there are a few things to note. This section will describe a couple different execution contexts and integration points at which JavaScript code is executed.

Global Context

There is only 1 global context – or global scope or global namespace. Any variable defined outside a function exists within the global context:

var x = 9;
function XManager() {
  var self = this;
  self.getX = function () { return x; }
  self.setX = function (value) { x = value; }
}

The global-scoped x variable is defined outside of the XManager function and assigned the value of 9. When getX is called, it will return the global-scoped x (the value of 9).

Local Scope – Function Execution Context

The alternative to the Global Scope is Local Scope. The local scope is defined by the function execution context:

var x = 9;
function XManager() {
  var self = this,
      x = 10;
  ...
  self.getInstanceX = function () {
    return x; // returns 10
  }
}

In this case, a variable x is declared twice. The first time is within the global execution context. This variable is accessible within XManager. Within the XManager constructor function, the private variable x is declared and initialized to 10. The getInstanceX method will return the variable x that is first in its execution context stack:

ecstack
Execution Context Stack (David Shariff)

The getInstanceX method is “Active Now”, XManager‘s private variable x is next, followed by the global-scoped variable x, and finally the global execution context. All of this is to explain why getInstanceX returns 10 and not 9. Powerful stuff!

let & Block-Level Scope

I cannot discuss execution contexts without mentioning the keyword let. This keyword allows the declaration of block-level scope variables. Like ES6 classes, if antiquated browsers need to be supported, the let keyword will not be available.

function Start() {
  let x = 9;          // variable assigned to value 9
  function XManager() {
    let x = 10;       // different variable assigned to value 10
    function getX() {
      console.log(x); // return 10
    }
    console.log(x);   // return 10
    getX();
  }
  console.log(x);     // return 9
  XManager();
}
Start();

A block scope variable is accessible within its context (Start) and contained sub-blocks (XManager). The main difference from var is that the scope of var is the entire enclosing function. This means, when using let, XManager and the contained sub-blocks (getX) have access to the new variable x assigned to the value of 10 while the variable x in the context of Start will still have the value of 9.

Event Handlers

Client-side JavaScript code is triggered by the user through DOM events as they interact with rendered HTML. When an event is triggered, its subscribers (read event handlers) will be called to handle the event.

HTML – Event Subscription

<div id="submit" onclick="clickHandler()">Button</div>

JAVASCRIPT – Event Subscription

var button = document.getElementById("submit");
button.addEventHandler('click', clickHandler);

JAVASCRIPT – Event Handler

function clickHandler() {
  console.log("Click event handled!");
}

Event handling marks the integration point between user interaction with HTML and the application API in JavaScript.

Understanding how to create objects and the Execution Context is important when writing client-side JavaScript. Designing the JavaScript as an API will help to further manage the pros and cons of the language.

Advertisements

Creating An ASP.NET MVC Project in Visual Studio 2015

Creating an ASP.Net MVC Project in Visual Studio 2015

Creating projects in Visual Studio 2015 is a guided process. This makes it a lot easier to create the correct project. The subsequent sections describe the process for creating an ASP.Net MVC project within Visual Studio 2015.

Prerequisites:

  • Visual Studio 2015 installed on a machine matching the recommended system specifications set by Microsoft

A New Project

The “New Project” dialog is used to create a new project in Visual Studio 2015. This can be opened in multiple ways:

  1. Start Page > Start list > “New Project…”
  2. File Menu > New > Project

OpenNewProjectDialog

Clicking “New Project…” from the Start list or navigating to “Project…” from the File > New menu will open the “New Project” Dialog. (Note: The dialog will look slightly different depending on the features and licenses installed).

FillingNewProjectDialog

To make sure the project is set up and configured properly by Visual Studio 2015 pay close attention to the following items:

  • .NET Framework version
    • This drop-down should contain all of the .NET Framework versions installed and supported by Visual Studio 2015
    • Select the version appropriate for your project. In this case, 4.6.2 is appropriate.
  • Project Type
    • Make sure to select the “ASP.NET Web Application (.NET Framework)” template to make sure you are not selecting a .NET Core version.
  • Name
    • This will name the ASP.NET MVC project. Name this according to established naming conventions of the organization. Generally it would use the following format: <Company Name>.<Project Name>.Web
  • Location
    • Select, Browse, or create a directory to contain the ASP.NET MVC project.
  • Solution Name
    • Name the solution file. If the “Create directory for solution” checkbox is checked, Visual Studio will create a directory for the solution named by the “Solution name” field. This solution directory contains all of the created projects. This is the default operation and is general considered best practice.

The next step is to click “OK”. The “New ASP.NET Web Application” dialog is displayed.

SelectATemplate

Within this dialog, make sure to choose the “MVC” template. An optional step is to include a Test project too. Then click “OK”.

Visual Studio will create the project based on the configuration settings. This may take a moment:

CreatingProjectProgress

When the creation process is complete, the project readme will open and the Solution Explorer will contain the solution and project:

ProjectCreateFinished

Enjoy your new project.

Did My Jasmine Expect Method Get Called?

When unit testing with Jasmine, expect() calls are not mandatory. That is, calling expect() at least once is not enforced by Jasmine. I recently ran into a problem which caused me to ask myself “did that expect method get called?”. I couldn’t count on Jasmine for this – in fact, my tests pass whether I include the expect() call or comment it out! So I went digging..

I determined that I could simply create spies for my expect() calls. This is an easy way to leverage Jasmine to inspect your tests. Simply create your spy:

const expectSpy: jasmine.Spy = spyOn(window, 'expect').and.callThrough();

I am using TypeScript for my unit tests. Since the expect() method is global and I am running my tests in a browser, I use the window object directly. There are ways to obtain the global object without this sort of hard-coding but, that is besides the point.

Moving on, the expect() calls must work properly so and.callThrough() is called. This is important. Without including and.callThrough(), your tests will fail because, rather than Jasmine’s expect() execution, you will be limited to a jasmine.Spy.

Here is a more complete example of a test with an expect spy – slightly modified from a sample Angular 2 application I have been working on:

it('should trigger on selection change', async(() => {
  const expectSpy: jasmine.Spy = spyOn(window, 'expect').and.callThrough();

  const triggerSpy = spyOn(component, 'triggerThemeChanged');
  const select = fixture.debugElement.query(By.css('select.theme-selector'));
  dispatchEvent(select.nativeElement, 'change');

  fixture.whenStable().then(() => {
    expect(triggerSpy).toHaveBeenCalledTimes(1);
  }).then(() => {
    expect(expectSpy).toHaveBeenCalledTimes(2);
  });
}));

There are a few things about this test that are not the point of this article – what the heck is async() and the apparent improper use of dispatchEvent()? The important bits are the use of Promises as implied by the use of then() callbacks, the creation of the expect spy, and the inspection of the expect spy.

The test creates the expect spy and then uses expect() as usual within the test until it finally inspects the expect spy. Remember, the inspection of the expect spy counts as an expect() call! This is why expect(expectSpy).toHaveBeenCalledTimes(2) is called with 2 rather than 1.

I stopped at the call count. This test could be extended to further leverage the Jasmine API by looking at expectSpy.calls with other handy methods to make sure the expect() calls were made properly. I’ll leave that for an exercise for the reader. Just make sure your testing, at a minimum, covers the scope of your problem.

If you have had similar issues or have explored this in more depth I would be very interested in hearing about your journey! Comments are welcomed and appreciated.

Meteor Hang-up: Extracting Package….

In the world of Node.js and NPM, things can change at an increasingly rapid pace. This causes pain when starting or upgrading projects that require NPM packages. While there are sites like Greenkeeper, I see them as symptoms of a flawed system. Yes, I will say that without offering alternative solutions because at the moment I am aware of exactly zero. Suggestions welcome!

It is a wonderful world of possibility.

Complaining about NPM is not the point of this article. I’ll stop wasting time:

Recently I came across a few excellent tutorials about using Meteor, Ionic 2, Angular and React. They eventually brought me to Telescope Nova. My first thought was: this looks promising.

After forking and cloning and other Gitisms, I was ready to start the application:

npm install
npm run start

Of course I have a Microsoft development background so when I saw a bunch of red because of ‘.sh’ I wondered why these two letters were such a problem. I ended up having to update my start script to exclude this bit of code. The script I excluded simply renames a sample_settings.json file to settings.json. I figured that was a safe thing to shortcut in this case by renaming it myself.

My next step was to try it again!

> Nova@1.0.0 start C:\Demo\Telescope
> meteor --settings settings.json

[[[[[ C:\Demo\Telescope ]]]]]

=> Started proxy.
=> Started MongoDB.
=> Extracting std:account-ui@1.2.17

To be honest, I let it try for a few hours and it just could not get that pesky package extracted. Certainly something had gone wrong before that. After digging into the depths of Nova, Meteor, and NPM, I finally explicitly searched within Stack Overflow for: Extracting std:accounts-ui.

The search came up with only 2 results which are both linked at the bottom of this article. Most importantly: following the suggestions solved my problem.

I fixed the issue by relocating the 7z executable (7z.exe) from: C:\Users\[UserName]\AppData\Local\.meteor\packages\meteor-tool\1.4.2_3\mt-os.windows.x86_32\dev_bundle\bin to a place outside of any source/build code/tools location. I relocated it because I didn’t want to mess up my machine any more than it already may have been. Turns out, the missing 7z.exe was all it took to get my Meteor package installed properly!

It figures that the solution was to create a sort of FileNotFound scenario.

In an effort to spread the word, the following links lead me to this solution:

http://stackoverflow.com/questions/41155583/meteor-1-4-2-3-adding-package-extracts-forever-windows

http://stackoverflow.com/questions/41195227/meteor-package-extracting-forever

https://github.com/studiointeract/accounts-ui/issues/67

https://github.com/meteor/meteor/issues/7688

I hope this helps. It is a rather simple solution in the end. I am very interested in learning of your past issues with our current favorite packaging system and its various dependencies. Feel free to comment if you have hard-fought wisdom to share!

UPDATE: just a quick update here, turns out this approach can be helpful when updating packages or if you get stuck here ‘Extracting meteor-tool@1.4.2_5’ (after the recent patch). Note: extracting meteor tools can take awhile (upward of 30+ minutes) so expect to wait awhile to know if it fails.

Bring Your Own Shell (Update 1.9 for VS Code)

I received the recent update for VS Code with pleasant surprises for the Integrated Terminal! Most importantly, it now defaults to Powershell. This can be changed using VS Code settings. This ability is not necessarily a new option within VS Code but, if you rather your own shell, then here we go!

Accessing Settings

To access VS Code settings, use the menu under File > Preferences and click Settings. A settings.json file opens with a list of Default Settings. These can be copied to your workspace or user settings.

With the Settings open, finding settings is easy – just type the setting name (or scroll) as shown in Figure 1.

settingsjson
Figure 1: Looking for ‘shell’ commands in settings.json

Bring Your Own Shell

According to VS Code Documentation, a different shell executable can be used given that it adheres to this very important requirement:

..the shell executable must be a console application so that stdin/stdout/stderr can be redirected..

This offers a lot of flexibility to support your given scenario and preferences. Update the shell using the format: “terminal.integrated.shell.platform”: “full path to shell executable”. For example, when specifying the setting for Windows this would be similar to:

"terminal.integrated.shell.windows":
    "C:\\WINDOWS\Sysnative\\WindowsPowerShell\\v1.0\\powershell.exe"

Shell Arguments

Arguments can be passed to this executable using the following format: “terminal.integrated.shellArgs.platform”: [“arg1”, …]. Specifying the setting for Windows would be similar to:

"terminal.integrated.shellArgs.windows": ["Get-Help", "*"]

-or-

"terminal.integrated.shellArgs.windows": ["Get-Help *"]

With those sample arguments, the terminal window will close after the help text displays for Powershell. While that is less than useful, the settings are there for your benefit. Choose the shell you want within VS Code and configure it accordingly. Of course, make sure you first have it installed.

Platforms

I’m sure you all noticed the “platform” placeholder within the setting formats. Currently the platforms for terminal settings specified within VS Code are:

  • linux
  • osx
  • windows

VS Code is awesome, what do you think? I am eager to hear of your experiences using Visual Studio Code!

Thankful for Integrated Terminals in Visual Studio Code

Since before I started my software development career, I have been using Visual Studio. It is a beast-mode IDE with tons of heavy-weight features and a bountiful supply of extensions. Don’t get me wrong, Visual Studio is near and dear. It has been the key to successful delivery of many kinds of projects. Since Visual Studio was so useful, I honestly wondered why Visual Studio Code was even created. After using it though, my thoughts changed from “why?” to “this is amazing!”

To be able to view everything on a single screen is hard to do – some would say unnecessary or even Noise. One of the great thing about VS Code is that it accomplishes the two feats of allowing a developer to quickly discover what they need during development without needing to wade through the noise. This is done by a simple tab-like interface including Explorer, Search, Git, Debug, and Extensions. The best part about this is the Integrated Terminal. It is very simple to get started, easily accessible, and easily ignored.

Integrated Terminals

vscintegratedterminal

My primary use for VS Code is front-end development. VS Code offers great tooling for creating high-quality user interfaces using the latest frameworks such as Angular 2 and React. Full-stack development can be done at once with a single language (JavaScript). With Integrated Terminals, Node.js operations can be performed quickly and easily.

With Extensions offering further integration, I find VS Code especially useful when developing with Node. Its Integrated Terminals allow an easy way of managing Node operations. When developing a MEAN stack application, each tier can get its own terminal for operations specific to that tier.

Dedicated terminals per tier is also beneficial because certain operations are long-running such as running MongoDB, Node and Angular. I tend to create a terminal per long-running operation. VSC makes it very easy to get these started – and to ignore them when they are not appropriate for the current task. For example, I can ignore the DB and Services when styling an Angular 2 component while still maintaining the benefit of them running so I can quickly test my work.

When writing front-end code, I would definitely consider Visual Studio Code.

Commands

  • Ctrl+`
    • Toggle Integrated Terminal Panel
  • Ctrl+Shift+`
    • Create New Integrated Terminal Instance
  • Ctrl+Shift+P
    • Begin searching the Command Palette

User Interface

vscintegratedterminalpane

Interact with Integrated Terminals like you would a Command Prompt. Multiple instances can be created while being accessible by simply making a selection from the drop-down. From the small toolbar, instances can be removed, more instances can be created, and the down-arrow closes the entire panel.

and to close,

Write End-to-End Tests for Your Angular 2 Applications With Protractor

Testing your applications is a critical step in ensuring software quality. While many agree, it can be hard to justice the budget for it. This issue can occur when development and testing are imagined as two separable activities. In fact, there are common practices in place designed around their coupling (see TDD). End-to-End (E2E) testing is another common practice designed in this way.

E2E testing can be thought of as an additional direction or angle in which to test an Angular 2 application’s logic. It tests, from a user’s perspective, if the application does what is expected. If these tests fail, your users will fail and the failure will be right in their face. This user-centric approach is critical to ensuring an intended user experience. Writing these tests will produce a detailed user experience specification enforced by simply making sure the tests pass.

End to End testing does not replace QA resources. All software is written by people and people are not perfect – no matter what they say.

Interacting with Your Application

To begin creating our tests we need a way to interact with the application. This is made easier with Protractor. With Protractor, Selenium can be leveraged within JavaScript including integration with Angular applications. A few critical components are exposed to you through Protractor.

browser – browser-scoped operations such as navigating to a particular URL.
element – provides a way to retrieve the UI components of your application from within your tests.
by – What UI component do you want and how should it be found?
promise – support asynchronous operations.
ElementFinder – perform operations on retrieved UI components.
ElementArrayFinder – perform operations on an array of retrieved UI components.

Importing from Protractor

Importing what you need from Protractor is as easy as importing anything else:

import { browser, element, by, promise, ElementFinder } from 'protractor';

Navigating to a URL

Get to the correct page using browser.get():

navigateTo() {
    return browser.get('/list');
}

Retrieving and Manipulating UI Components:

Use the Protractor API to retrieve elements and perform operations in your application:

clickEditButton(): promise.Promise {
    return element(by.css('.edit-button')).click();
}

Creating Page Objects

Now that a few fundamentals are out of the way, lets take a look at organizing our tests. First, we need to create Page Objects. These objects encapsulate interactions with UI components. Implementing Page Objects could be thought of as user experience mapping including structure and operations.

With single page applications, a “Page Object” could get quite unwieldy! This is why we need to consider the structure of the application. Considering the Angular Components within the application is a great way to begin dividing your Page Objects. Take a simple Todo application shown in Figure 1:

todoscreenshot
Figure 1: Sample todo application

Even with this simple application there is a lot to include in just a single Page Object. This screen can be divided up into four distinct areas: header, menu, list, and details. Let’s look at how these can be created using separate Page Objects:

Header

todoheader

// header.po.ts
import { promise, ElementFinder } from 'protractor';

export class Header {
    getContainer(): ElementFinder {
        return element(by.css('.header'));
    }
    getHeader(): ElementFinder {
        return this.getContainer().element(by.css('.header-text'));
    }
    getHeaderText(): promise.Promise {
        return this.getHeader().getText();
    }
}

Menu

todomenu

// menu.po.ts
import { element, by, promise, 
    ElementFinder, ElementArrayFinder } from 'protractor';

export class Menu {
    getContainer(): ElementFinder {
        return element(by.css('.menu'));
    }
    getMenuItems(): ElementArrayFinder {
        return element.all(by.css('.menu-item'));
    }
    getActiveMenuItem(): ElementFinder {
        return this.getContainer()
            .element(by.css('.menu-item.active-menu-item'));
    }
    getActiveMenuItemText(): promise.Promise {
        return this.getActiveMenuItem().getText();
    }
    getCompletedMenuItem(): ElementFinder {
        return this.getContainer()
            .element(by.css('.menu-item.completed-menu-item'));
    }
    getCompletedMenuItemText(): promise.Promise {
        return this.getCompletedMenuItem().getText();
    }
    getAddMenuItem(): ElementFinder {
        return this.getContainer().element(by.css('.menu-item.add-menu-item'));
    }
    getAddMenuItemText(): promise.Promise {
        return this.getAddMenuItem().getText();
    }

    clickActiveMenuItem(): promise.Promise {
        return this.getActiveMenuItem().click();
    }
    clickCompletedMenuItem(): promise.Promise {
        return this.getCompletedMenuItem().click();
    }
    clickAddMenuItem(): promise.Promise {
        return this.getAddMenuItem().click();
    }
}

List

todolist

// list.po.ts
import { element, by, promise, 
    ElementFinder, ElementArrayFinder } from 'protractor';

export class List {
    getContainer(): ElementFinder {
        return element(by.css('.list'));
    }
    getItems(): ElementArrayFinder {
        return element.all(by.css('app-todo'));
    }
    getItem(index: Number): ElementFinder {
        return this.getItems().get(index);
    }
    getEditButton(index: Number): ElementFinder {
        return this.getItem(index).element(by.css('.edit'));
    }
    getDeleteButton(index: Number): ElementFinder {
        return this.getItem(index).element(by.css('.delete'));
    }

    clickEditButton(index: Number): promise.Promise {
        return this.getEditButton(index).click();
    }
    clickDeleteButton(index: Number): promise.Promise {
        return this.getDeleteButton(index).click();
    }
}

Details

tododetails

// details.po.ts
import { element, by, promise, ElementFinder } from 'protractor';

export class Details {
    getContainer(): ElementFinder {
        return element(by.css('.details'));
    }
    getDetailHeader(): ElementFinder {
        return this.getContainer().element(by.css('.detail-header'));
    }
    getDetailHeaderText(): promise.Promise {
        return this.getDetailHeader().getText();
    }
    getDescription(): ElementFinder {
        return this.getContainer().element(by.css('.detail-description'));
    }
    getDescriptionText(): promise.Promise {
        return this.getDescription().getText();
    }
}

Alright, that was a lot of code. Let’s take a step back for a moment. We are creating Page Objects representing the distinct areas of the UI that we have determined. Each Page Object has offered the ability to retrieve (e.g. getContainer) and operate (e.g. clickDeleteButton) on UI elements from their respective areas. The last item we need now is a root Page Object to complete our Page Object hierarchy.

The Page Object Hierarchy

todopageobjecthierarchy

Yes, I can’t seem to help it – there is one additional Page Object that has been included along with the root Page Object. The Item Page Object will encapsulate the structure and logic of each todo item within the List.

An instance of each leaf Page Object (which includes header, menu, list, and details) is stored on the root Page Object (TodoApp). This provides the ability to write complex operations while exposing a simple API to your tests:

// snippet todo-app.po.ts

export class TodoApp {
    constructor() {
        this.list = new List();
    }
    private list: List;

    removeAllItems(): promise.Promise&lt;void[]&gt; {
        let promises: Array&lt;promise.Promise&gt; =
            new Array&lt;promise.Promise&gt;();
        this.list.getItems().each(item =&gt; {
            promises.push(item.clickDeleteButton());
        });
        return promise.all(promises);
    }
}

In removeAllItems() each todo item is found and its Delete button is clicked. We should no longer have any todo items. This is a testable scenario. Testing this would mean answering the question – what happens when there are no items? We can use our Page Objects to create tests around this scenario!

Testing with Page Objects

Creating tests using Page Objects can clean up your tests and allows more explicit definition of your test scenarios. This way also helps keep the user interface definition out of the tests making it easier to maintain – keep in sync with your application!

Jasmine Syntax

If you have written tests using Jasmine before, you know how to create tests for Protractor. It is a great tool for writing unit tests! It is just as good for writing tests with Protractor. Simply follow their tutorials to learn more about Jasmine.

Writing Tests

Now lets see some tests. We will test the ability to remove all items by clicking their Delete button:

// todo-app.e2e-spec.ts
import { TodoApp } from './todo-app.po.ts'

describe('Todo Item', () =&gt; {
   let page: TodoApp;
   beforeEach(() =&gt; {
      page = new TodoApp();
   });

   it('delete button should remove todo item', (done) =&gt; {
      page.navigateTo();
      const text: String = 'test text';
      page.addItem(text, text).then(() =&gt; {
          page.removeAllItems().then(() =&gt; {
             expect(page.getItems().count()).toBe(0);
             done();
          });
      });
   });
});

This test sample is following a few common practices. First, the root Page Object is imported:

import { TodoApp } from './todo-app.po.ts';

Next, the top-level test suite is defined. Within this test suite a variable is defined to hold our root Page Object. Then comes the initialization of each test in the suite:

beforeEach(() =&gt; {
    page = new TodoApp();
});

This is a fairly rudimentary example but, the initialization code will run once before each test in the suite. Make sure to place any necessary test initialization code within this block such as initializing Page Objects and setting up the UI.

Next comes the fun. The test is defined using typical Jasmine syntax with support for asynchronous test code:

it('delete button should remove todo item', (done) =&gt; {
   page.navigateTo();
   const text: String = 'test text';
   page.addItem(text, text).then(() =&gt; {
       page.removeAllItems().then(() =&gt; {
          expect(page.getItems().count()).toBe(0);
          done();
       });
   });
});

The first step in our test is to navigate to the TodoApp and create a variable to hold our new item text and description.

Considering that the test is for ensuring items get deleted when their Delete button is clicked, we need to be sure there is an item to remove! Using a Page Object method for adding an item, a new todo item is added to the screen using the new item text and description defined earlier. Since the method returns a promise, we use then() to continue execution.

We have added an item. Now its time to remove it. We know that the Page Object contains a method that clicks a todo item’s Delete button. We also know that the Page Object provides the ability to remove all of the todo items in the list using this method. This means we can simply call removeAllItems() and check the list to make sure it is empty.

If the test passes we can say the Delete button works for each todo item.

Mean TODO

There is a sample application demonstrating Angular 2 in the MEAN Stack that includes a set of E2E tests. Simply follow the guide on GitHub to get started!

Thank you for reading this far! If you have any comments, questions or concerns please send a message.