1.  


  2.  


  3.  


  4. How to Write Protractor Tests Properly

    Most of us, developers, don’t like writing integration tests. But what’s there not to like? They allow us to make sure that a newly added feature provides correct interaction as it was defined, as well as to check that the same feature doesn’t break the existing functionality. So, we could devote several hours to writing them to get satisfaction from all green passed tests.

    However, the nightmare arrives quite fast - maintenance of end-to-end (e2e) tests. Any small addition of a new item to a navigation bar is leading to the fail of 40% of tests. This article is about building the proper level of abstractions such that minimum or no changes would be required to maintain the tests.

    Raising Abstractions
    Why e2e tests break? Their implementation is very coupled to the structure of the page.

     image

    By introducing the page object, we can raise the level of abstraction over our page such that test would use page object, those, in turn, will be aware of page structure.

    What’s a Page Object?
    Page Object is a conceptual model of a certain part of the UI with its properties and methods. Their the purpose is similar to a domain specific language (DSL): to provide an abstraction layer that will describe interactions of user with the page, decoupled from its implementation. The page above can be decomposed into Main, Filters, and Item Objects.

     image

    How to write a Page Object?
    Page objects are aware of the whole page implementation. The hold references to the selectors, do clicks, etc.

    For example, the implementation of the filters object can be the following:  

    function Filters() { 
        this.container = element(by.css('.filters-container')); 
        this.list = element.all(by.repeater('filter in filters'));
        this.select = function (label) { 
            element(by.cssContainingText('.filter-item', label)).click();
        }; 
        this.isSelected = function (label) { 
            return this.container.element(by.css('selected'))
                .then(function(text) { 
                    return text === label; 
                }); 
            }; 
        };
    }

    Filters object is just a JavaScript class with attributes and methods that can be done on filters. It has a reference to the filters DOM container, references to the list. Those attributes will be used later in scenario to check the correct view of the filter list. 
    Methods are required to check interaction with filters such as selection a certain filter by the name and to make sure that it’s selected.

    Scenarios
    Scenarios describe how a user will interact with the application, e.g. filling the form, deleting an item, filtering, navigating, etc.

    You might consider it useful to define a scenario in a table form as following: 

    image

    Scenarios only implement assertions on page objects without any dive into page internals.

    For example:

    describe(‘Initialization’, function () {
    	var page, filters;
    	
    	beforeEach(function () {
    		page = new Page();
    		page.load();
    		filters = new Filters();
        });
        
        it(‘should check that filters a displayed’, function () {
        	expect(filters.container.isDisplayed()).toBe(true);
        });
    });
    
    describe(‘Filtering’, function () {
    beforeEach(function () { ... }); it(‘should select Item One filter’, function () { filters.select(‘Item One’); expect(filters.isSelected(‘Item One’)).toBe(true); ... }); });

    Thus, the change of underlying page structure would affect only page object and require minimum changes.

    This approach will allow you to decouple your business interactions from page implementation. If any changes are done to the page, it’s enough to change the page object, all scenarios should keep working. It allows to perform regression tests. In case of  a new feature, you need to add/change page object and write the corresponding scenario.

     


  5.  


  6. AngularJS: differences between service/factory/provide

    When starting with AngularJS, it’s important to realize the difference angular components: service, factory, provider, and value.

    This post on stackoverflow, which was born from this post in angular mailing list, explains the a great depth the difference between those notions including examples from Misko.

     


  7. Mobile Device Emulation with Chrome Dev Tools

    So, Google IO/14 is over. One of its main themes in web sphere was mobile. Mobile first. It’s growing. 1/3 of web sites visitors come from there. 

    Google pushes web platform and mobile forward by introducing polymer, web components, service workers, caring about mobile performance. One of the talks was devoted to the handy new feature that landed in Chrome Canary day before IO14 started - Device Emulation Mode. To be fare, Canary already had it placed in console drawers in dev tool but now it became very interactive.

    This article describes capabilities that the device emulation mode provides. Please note, this feature is available in Chrome Canary for now.

    Start

    For a start, open dev tool in Canary, and next to the Elements tab, you will notice the mobile icon.

    image

    This will trigger the emulation mode of the currently opened page.

    image

    Pay attention to the yellow line above the page itself. It will ask you to reload the page.

    There are two aspects that you can notice immediately: you simply resize the viewport and see how your website adapts to it, and the default emulation of touch events.

    Device Settings

    Top left corner, in orange, contains device settings. You can choose different type of devices that you’d like to test. List is pretty impressive. It has more than 50!!! different types of devices of popular vendors (Apple, HTC, Google, Samsung, etc.)

    image

    You can also set the width, height and rotation of the device, as well as its device pixel ratio to test your images on high dpi screens. The fit flag allows you to see the website either in full size or scaled to fit your screen.

    Media Queries

    Under the device settings part you can notice the media queries bars. To open them, click on the bars icon in the top left corner. What you will see is bars that correspond to the different media queries in your css. 

    image

    By clicking on one of them, your website will immediately rescale. And if you make a right click on any bar, you can navigate to its css resource.

    image

    Network

    On the right from the device settings panel, in blue, i can notice another one - network. This panel would allow you to choose the desired connection to test on whether it’s a wifi, 3G or even offline.

    image

    More

    On the right, far away from the network, you might notice three dot. 

    image

    If you click on them, dev tool will open the emulation draw where you can configure even more options.

    image

    For example, you can set the parameters of difference sensors. Set a latitude and longitude of geolocation or set angles for accelerometer.

     


  8. Mocking requireJS dependencies is a vital capability for proper unit tests. There are many solutions like Squire, Isolate, and testr that allows to do that. 

    But none of them works properly in Karma test runner. Mocker, using different contexts of requirejs, allows to mock dependencies of a module under testing.

     


  9. Note on static analysis of JavaScript

    This note is born due to the sentence that Igor Minar mentioned in JavaScript Jabber podcast episode on AngularJS. Here’s the whole passage.

    At Google, a lot of the code in JavaScript is statically analyzed using the Closure Compiler. And almost all JavaScript code is annotated using type annotations that come from the closure extension to JavaScript. I don’t know how to correctly describe it. So, Closure just uses common blocks to define what type an article or thing is. And you can describe interfaces in this way just like you would in a static language. And then the Closure Compiler can actually force that you’re passing the right type into the right function. And using this information, not only can it give you validation of your code or provide some feedback on correctness of your code, but it also can improve the minification capabilities. Because once the compiler knows about the structure of the code, it can change the structure of the code in a way that no other minifier can.

    So, what do is it give us? Besides the minification capabilities, the annotation and enforcement of types mainly influences on performance. If we don’t mess up types of JavaScript data structures (e.g don’t put numbers into array of strings), most of JS engines (V8, SpiderMonkey) know how to optimize them. This leads to better performance.

     


  10. Together with this, it’s totally worth to listen to JavaScript Jabber podcast episode about Hypermedia API.

     


  11. Notes on Website Performance Optimization Udacity course

    Lesson 0

    1. The DOM construction happens over the time in the following manner: html string -> tokens -> html nodes -> DOM.
    2. In dev tool timeline hit cmd+shift+r to will trigger browser hard reload of the page AND record the whole loading process in the timeline.

    Lesson 1 - The critical render path

    1. CSS properties are cascade down to its children.
    2. Simple CSS rules are parsed faster.
    3. Hit right click on time line to load or save it.
    4. Recalculate style (purple in timeline) is in charge of building CSSOM.
    5. Render tree represents only visible node, meaning head tag or nodes with display:none are not its’ parts.
    6. Layout step is calculating the position and dimensions of visible DOM node.
    7. Viewport meta tag sets the width property for css. Otherwise browser default viewport with is 980px.
    8. Batch updates to avoid multiple layouts.

    Lesson 2 - Optimizing CPR

    1. Separate media styles into different files and media attribute to link tag, e.g. <link href=”…” media=”print”> to prevent rendering blocking.
    2. Add async attribute to the script tag to prevent the loading js from blocking the CRP.
    3. Always minify, compress, and cache.
     


  12.  


  13. Composing Discrete Events with RxJS

    DOM events are very rich but badly composable. If we need a discrete conceptual move event, it would demand subscription to 3 DOM events: mousedown, mousemove, and mouseup.
    Below in the code in vanilla JavaScript.

    var moveEvent = {};
    
    function mouseDownHandler(ev) {
      document.addEventListener('mousemove', mouseMoveHandler, false);
      moveEvent.start = {
        x: ev.clientX,
        y: ev.clientY
      };
    }
    
    function mouseMoveHandler() {
      document.addEventListener('mouseup', mouseUpHandler, false);
    }
    
    function mouseUpHandler(ev) {
      moveEvent.target = ev.target;
      moveEvent.stop = {
        x: ev.clientX,
        y: ev.clientY
      };	
      document.removeEventListener('mousemove', mouseMoveHandler);
      document.removeEventListener('mouseup', mouseUpHandler);
      moveHandler(moveEvent);
    }
    
    function moveHandler(ev) {
      var body = document.querySelector('body');
      body.innerHTML = 'Start: x = ' + ev.start.x + ', y = ' + ev.start.y + '; Stop: x = ' + ev.stop.x + ', y = ' + ev.stop.y;
    }
    
    document.addEventListener('mousedown', mouseDownHandler, false);
    

    Live example on JSBin

    On mousedown, we register a listener to mousemove, and in its handler subscribe to mouse up. Mousedown handler extracts the coordinates start, and the mouseup handler extract stop coordinates and removes event listeners.

    The code is not long or complex but not readable.

    RxJS implements the concepts of reactive programming. The main idea (in a nutshell) is working with streams using LINQ operators and schedulers. It has insane amount of methods that can be applied. The authors neatly divided it into categories.
    Below is the code example that is required to reach the same results but only with RxJS.

    var mouseDowns = Rx.Observable.fromEvent(document, 'mousedown');
    var mouseMoves = Rx.Observable.fromEvent(document, 'mousemove');
    var mouseUps = Rx.Observable.fromEvent(document, 'mouseup');
    
    var moves = mouseDowns.selectMany(function (md) {
      var start = {
        x: md.clientX,
        y: md.clientY
      };
      return mouseMoves.combineLatest(mouseUps, function (mm, mu) {
        var stop = {
          x: mu.clientX,
          y: mu.clientY
        };
        return {
          start: start,
          stop: stop
        };
      }).takeUntil(mouseUps);
    });
    
    moves.subscribe(function (res) {
      var body = document.querySelector('body');
      body.innerHTML = 'Start: x = ' + res.start.x + ', y = ' + res.start.y + '; Stop: x = ' + res.stop.x + ', y = ' + res.stop.y;
    });
        

    Live example on JSBin

    As you may notice, the code becomes more elegant and self-explanatory. We subscribe to mousedown event, extract the its coordinates, and then start listening to mousemove events till mouse up event have occurred. From last event we retrieve the coordinates of stop and return the resulting discrete move event.

    The concepts of RxJS are very powerful that allows us to do less with more.

     


  14. RxJS Resources

    RxJS is an awesome library parted by Microsoft from C# that enables reactive paradigm in javascript.

    The amount of learning resources is very limited and not easy to find. Below is the list of the most useful one.

    1. Getting Started
    2. Operators be Categories
    3. Examples’ Implementations
    4. RxJS for beginners - series of blog posts from Microsoft (14 parts)
     


  15. Apart of the dissertation of a guy who invented REST, this presentation with lot’s of text contains the best explanations if RESTful concepts.