AngularJS

Test code separation

Posted on by  
Richard Rijnberk

As someone who spends quite some time writing and checking unit and e2e tests I’ve started noticing a trend I’m somewhat confused by. There have been multiple occasions in which I’ve encountered test logic (repeatable and single use) in either test specifications or page objects. So I decided to share my approach to writing and foremost separating my test code into three categories. Those being: Specifications , Sequences and Page Objects. I’ll describe my views on these categories below.

The first category is the one we all use the most. It is the bread and butter of testing and describes our tests. For me this always follows the same general steps.

  • The setup where we set required variables and states,

  • the execution where we call the functionality we’ll be testing and

  • the validation where we check the result and/or side effects.

Continue reading →

Simplify your Protractor tests using Generator functions

Posted on by  
Auke Speksnijder

Writing protractor tests can be quite difficult, because of all the asynchronous calls you have to deal with. Even promise-chaining does not help when your tests become longer and more complex. With Javascript generator functions it is possible to simplify your tests.

Let’s say we have a todo-app created in AngularJS with two pages: a page with a list of todos and a page where a user can create a todo-item. We have two page objects created that can communicate with the pages in our Protractor tests. This is an example of an actual testcase with the use of promise chaining:

As you can see, the testcode is much easier to understand when the generator method is used.

Continue reading →

Correlate your services logging with Spring Boot

Posted on by  
Peter Steman

In a modern service landscape, especially when using containers, you are probably using something like the ELK stack (Elasticsearch, Logstash, Kibana) to flow all the logging into. But how to find from all those loglines what caused the nasty bug after a innocent buttonpress? One of the easy answers to this is what’s called a correlation id - basically a unique number assigned to that buttonpress which gets carried around between the services and added to every logline. Sounds good you say? it is so let’s see how to do this.

Continue reading →

Caching HTTP requests in AngularJS

Posted on by  
Niels Dommerholt

In AngularJS, especially when you’re using a 'modern' Web Component like approach, you often have directives request the same information from your services multiple times. Since we’d rather not do round-trips we don’t need to to save on server resources caching is our go-to solution. In this post I will show two different approaches to caching resources: the built-in angular way using $resource and a home-grown solution.

Original post

Continue reading →

Expandable list component for AngularJS (1.5)

Posted on by  
Richard Rijnberk

For several of my projects I required a list where input items could be dynamically added and removed. Because i saw uses for this over and over i created a component which i'm sharing with you here. The component ended up like the code below. Where i used a template generation function in order to create the ul and li elements. I'm using the angular.element function to create nodes as a method of preference.

function mpExpandableListController(){
    var vm = this;

    vm.add = add;
    vm.manipulatable = true;
    vm.remove = remove;

    // If items was not declared, create new array.
    if(!vm.items) {
        vm.items = [];
    }

    // If the items array is empty, create first item.
    if(vm.items.length === 0) {
        add();
    }

    /**
     * Add an item to the item list.
     */
    function add(){
        vm.items.push({});
        setManipulatable();
    }

    /**
     * Remove an item from the item list.
     * @param item The item to remove
     */
    function remove(item){
        vm.items.splice(vm.items.indexOf(item), 1);
        setManipulatable();
    }

    /**
     * Set the flag which designates that the list may be manipulated.
     */
    function setManipulatable() {
        vm.manipulatable = vm.items.length > 1;
    }
}

/**
 *
 * @param $element The element as declared in the HTML
 * @param $attrs The attributes for said element
 * @returns {string} A template for this component.
 */
function template($element, $attrs){
    var container = angular.element('<ul>'),
        item = angular.element('<li ng-repeat="item in list.items">'),
        footer = angular.element('<li>');

    container.addClass($attrs.universalClass);
    item.addClass($attrs.itemClass);
    footer.addClass($attrs.footerClass);

    item.html($element.find('item').html());
    footer.html($element.find('footer').html());

    container.append(item);
    container.append(footer);

    return container[0].outerHTML;
}

var mpExpandableList = {
    bindings: {
        footerClass: '@',
        itemClass: '@',
        items: '=',
        universalClass: '@'
    },
    controller: mpExpandableListController,
    controllerAs: 'list',
    template: template
};

angular
    .module('my.project')
    .component('mpExpandableList', mpExpandableList);

Continue reading →

Grasping AngularJS 1.5 directive bindings by learning from Angular 2

Posted on by  
Emil van Galen

In AngularJS 1.5 we can use attribute binding to allow easy use of input-only, output-only and two-way attributes for a directive or component. Instead of manually parsing, watching and modifying attribute values through code, we can simply specify an attribute binding by adding a property to the object hash of:

Continue reading →

Using `$q.defer()` in AngularJS? Try the $q 'constructor' instead.

Posted on by  
Emil van Galen

Although I'm a great fan of using the ($q) Promise API in AngularJS, I never really liked using $q.defer() and its Deferred API. I always found using var deferred = $q.defer() together with $.resolve(..) and $.reject(..) to be too verbose. After recently checking the $q service documentation I stumbled upon the $q constructor that results in way less verbose code. To illustrate the usage of the $q constructor I will create a function that wraps the result of a Geolocation#getCurrentPosition invocation as an AngularJS $q promise. Using the traditional $q.defer() approach the function wrapper will look like this.

/\*\* @return {Promise} \*/
function getGeoLocation() {
    var deferred = $q.defer();

    $window.navigator.geolocation.getCurrentPosition(
        function(position) { // success callback
            return deferred.resolve(position);
        },
        function(positionError) { // error callback
            return deferred.reject(positionError);
        });

    return deferred.promise;
}

Continue reading →

Unit testing an AngularJS directive's private functions.

Posted on by  
Richard Rijnberk

As we all know Javascript gives us the awesome ability to create functions inside functions. This allows us to create private functions which support the main function. It is also something we do often when creating object functions. This structure is used by angular for the creation of providers and directives alike. Every once in a while I personally come to a point where I would like to test these private functions. This is especially true for use cases in Angular such as directives.I'd like to be able to run unit tests for a directive's private functions, but I'd like to do this without having to make them public. The way I do this is by using a concept called reflection. This process actually described by Bob Gravelle in his post 'Accessing Private functions in Javascript' actually exposes the private functions by using the toString method of a function. Before I go into specifics let me say that this article should only be used as an approach  for unit testing. There is a good reason for keeping private functions private and using this concept for application code may very well introduce interesting side effects. That being said let's go into details. In order for us to use this concept we'll need to make some slight changes to our directive. Normally we would declare our Directive Definition Object (DDO) and directly return it. As below:

return {
  restrict: 'E'
  ...
}

Continue reading →

Communication between Angular Controller and Directive

Posted on by  
Niels Dommerholt

Since I had issues finding a good explanation on how to tie together a controller and a directive with isolated scope I decided to create my own blog post on this subject. This repo contains a runnable example of the solution. It contains a Spring Boot Web Application that can be started to act as a HTTP server but all the interesting stuff is in the src/main/webapp folder.

To create modular code with AngularJS you want to create reusable components; directives. Directives should not depend in any way on the parent controller. They should not be able to see any of the parent scope unless it's explicitly provided to them. To do this Angular directives can have an isolated scope (which in my opinion should be the default). This however leads to an issue: typically a directive needs information provided for them, needs to provide methods that can be called and often also has to fire events that the layers above the directive need to be able to respond to. Especially the latter part, informing the scopes above of changes, is done in a somewhat particular way.

Continue reading →

ngImprovedTesting 0.3: improved ModuleBuilder with lots of bug fixes

Posted on by  
Emil van Galen

NOTE: ngImprovedTesting is AngularJS library to make mock testing AngularJS code more easy.
For more information about ngImprovedTesting be sure to read its (updated) introductory blog post.

Just released version 0.3 ngImprovedTesting with a much improved ModuleBuilder. Prior to 0.3 usage of ngImprovedTesting might be troublesome due to fact that the ModuleBuilder:

Continue reading →

Stateless Spring Security Part 3: JWT + Social Authentication

Posted on by  
Robbert van Waveren

This third and final part in my Stateless Spring Security series is about mixing previous post about JWT token based authentication with spring-social-security. This post directly builds upon it and focusses mostly on the changed parts. The idea is to substitude the username/password based login with "Login with Facebook" functionality based on OAuth 2, but still use the same token based authentication after that.

The user clicks on the "Login with Facebook" button which is a simple link to "/auth/facebook", the SocialAuthenticationFilter notices the lack of additional query parameters and triggers a redirect leading the user of your site to Facebook. They login with their username/password and are redirected back, again to "/auth/facebook" but this time with "?code=...&state=..." parameters specified. (If the user previously logged in at facebook and had a cookie set, facebook will even instantly redirect back and no facebook screen is shown at all to the user.) The fun part is that you can follow this in a browsers network log as it's all done using plain HTTP 302 redirects. (The "Location" header in the HTTP response is used to tell the browser where to go next)

Continue reading →

shadow-left