Posts by Richard Rijnberk

What it means for me to work at JDriven

Posted on by  
Richard Rijnberk

As I’ve recently posted on LinkedIn I’ve been a part of JDriven for seven years. This is as close to its conception as I could get. In this post I’ll try to explain what it means for me to be a part of this awesome company.

Working for JDriven means working with colleagues who have a passion for what they do.

Continue reading →

Extending Selenium with page objects

Posted on by  
Richard Rijnberk

As all who have used it know Selenium is a powerful tool when testing front-end applications. I personally use it in combination with protractor. This is because most of the work I do is with Angular and AngularJS applications. When you are using Typescript extending classes is an easy thing. In light of this I’ve been experimenting with new approaches to creating page objects.

The experiments started out by creating a class and then passing the "container" to it’s constructor. This is a powerful mechanism which has served me well during my time working with non-Typescript AngularJS. But the downside for this approach is that you’d have to expose each and every API function Selenium gives you. Even if you’d only expose those functions you’d need; it would still feel like a hassle. The extensions would look something like this:

And though this works and makes it all very explicit there had to be a better way. So when looking into the API for Selenium it exposes two classes which are exactly what we need. These being: ElementFinder & ElementArrayFinder.

Continue reading →

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 →

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 →

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 →

Web-components like AngularJS directives

Posted on by  
Richard Rijnberk

As you may already know web components consist out of a set of technologies which are combined to create a custom element for use in your HTML markup. The main additions, as described in several blogposts, are HTML imports, Shadow Dom and Templates combined with isolated scripts and styling. (If these concepts are new to you i suggest you read up on web components at WebComponents.org). This blog post has a living example on plnkr.co. If we look at Angular it already supports html imports and isolated scripts through it's directive approach. This means we can already create custom components by using directives. The downside of this approach however is that there is no true isolation of markup and styling. Meaning both markup and styling may be inadvertently influenced by an outside source. Let's start with a basic directive and template:

angular.module('shadow.app', ['component.api'])
.directive('simpleDirective', function() {
    return {
      restrict: 'E',
      replace: false,
      templateUrl: 'template.html',
      transclude: true,
      scope: {
        dynamic: '='
      },
      link: function($scope, element) {
        // your code here
      }
    };
  })

Continue reading →

Javascript oneliners: functions are attributes too

Posted on by  
Richard Rijnberk

Just a small reminder. Javascript allows you to call methods based on their name. So if a DOM element has a addClass and removeClass which both take the same argument we could write:

var someClass = 'some-class';
var hasClass = element.hasClass(someClass);
if(hasClass){
    element.addClass(someClass);
} else {
    element.removeClass(someClass);
}

Continue reading →

Creating a superelipse with canvas

Posted on by  
Richard Rijnberk

Today a colleague asked a group of front-end developers how he would create a superelipse. His current solution was to use a svg mask to remove all non essential visual information. This solution however had a setback, because we used a mask to shield the edges we had no real transparency. Thus we were unable to effectively use it on more graphic backgrounds. I however thought it should be able to use canvas to provide the solution. The code below is my solution. 

<canvas id="myCanvas" width="200" height="200"></canvas>
<script>
    var canvas = document.getElementById('myCanvas');
    var image = canvas.getContext('2d');

    var width = canvas.width;
    var height= canvas.height;
    var img = document.createElement('IMG');

    var shape = {
        beginPath : function(node) {
            image.beginPath();
            image.moveTo(
                    node.x,
                    node.y
            );
        },
        createCurve : function(curve, node) {
            image.quadraticCurveTo(
                curve.x,
                curve.y,
                node.x,
                node.y
            );

        },
        node : {
            top_left : {
                x : ((width/100)*20),
                y : ((height/100)*5)
            },
            top_right : {
                x : ((width/100)*80),
                y : ((height/100)*5)
            },
            right_top :{
                    x : ((width/100)*95),
                    y : ((height/100)*20)
            },
            right_bottom :{
                x : ((width/100)*95),
                y : ((height/100)*80)
            },
            bottom_right : {
                x : ((width/100)*80),
                y : ((height/100)*95)
            },
            bottom_left : {
                x : ((width/100)*20),
                y : ((height/100)*95)
            },
            left_bottom : {
                x : ((width/100)*5),
                y : ((height/100)*80)
            },
            left_top : {
                x : ((width/100)*5),
                y : ((height/100)*20)
            }
        },
        curve : {
            top : {
                x : ((width/100)*50),
                y : 0
            },
            top_right : {
                x : ((width/100)*92.5),
                y : ((height/100)* 7.5)
            },
            right : {
                x : width,
                y : ((height/100)* 50)
            },
            bottom_right : {
                x : ((width/100)*92.5),
                y : ((height/100)*92.5)
            },
            bottom : {
                x : ((width/100)*50),
                y : height
            },
            bottom_left : {
                x : ((width/100)*7.5),
                y : ((height/100)*92.5)
            },
            left : {
                x : 0,
                y : ((height/100)*50)
            },
            top_left : {
                x : ((width/100)*7.5),
                y : ((height/100)*7.5)
            }
        }
    }

    img.onload = function() {
        shape.beginPath(shape.node.top_left)

        shape.createCurve(shape.curve.top, shape.node.top_right);
        shape.createCurve(shape.curve.top_right, shape.node.right_top);
        shape.createCurve(shape.curve.right, shape.node.right_bottom);
        shape.createCurve(shape.curve.bottom_right, shape.node.bottom_right);
        shape.createCurve(shape.curve.bottom, shape.node.bottom_left);
        shape.createCurve(shape.curve.bottom_left, shape.node.left_bottom);
        shape.createCurve(shape.curve.left, shape.node.left_top);
        shape.createCurve(shape.curve.top_left, shape.node.top_left);

        image.closePath();
        image.clip();
        image.drawImage(img, 0, 0, width, height);
        image.restore();
    }

    img.src = "http://goo.gl/pC8iIF";

</script>

Continue reading →

JavaScript: console logging (with IE safety)

Posted on by  
Richard Rijnberk

Every once in a while I work on a site which has some or copious amounts of javascript. Now I do not mind this at all. But it's pretty tedious stuff writing the code and putting in loggers. And when you're working on something and you have to test it on IE. Well let's just say the console may cause some problems. But rather then removing all the logging i've found there's an easy solution. Building yourself a logger like structure which checks the existence of the console before writing. That way you can add logging statements without crashing the entire application. A sample logger would look like this:

logger={
    log: function(message) {
        if(window.console && console.log) console.log(message)
    },
    dir: function(message) {
        if(window.console && console.dir) console.dir(message)
    }
}

// We can call this like so:
logger.log($("head title").text());

// or so:
logger.dir($("body"));

Continue reading →

Javascript, keeping it clear

Posted on by  
Richard Rijnberk

Note that this blog is in no way written as a "best practice" or "do it this way" kind of blog. I am not, nor do I aspire to be, the worlds greatest javascript programmer. I do however like my code clear and structured. Now lately some collegues have asked me how I write my code and that in turn prompted this blog. In short the best way to keep your javascript clear is using namespaces. The use of namespacing is very simple and should cause you no problems. As you will come to see it will be both easy and clear for fellow developers to read and modify your code. So yes, if you wish to remain the javascript magician with obscure code that no other developer wants to touch feel free to not use them. Creating a namespace:

var namespace ={
}

Continue reading →

shadow-left