[Not finished yet]

We will start with a gulp angular seeded project. Why an angular project? Because currently my team is using angular

#1. Create the scaffold

yo gulp-angular

If you get the following error message: You don't seem to have a generator with the name gulp-angular installed, install the generator first with npm install -g generator-gulp-angular (note the generator- part). Again if you get another error: The package express does not satisfy its siblings' peerDependencies requirements!, replace -g with -G. I got it when I install with Gitbash on Windows, and haven’t verified on other operating systems. More information, please find this SO question. The error is not exactly the same by the way.

I chose Angular version 1.3.x, with no jQuery, no REST library ($http is enough), with UI Router, Bootstrap, Sass.

After generated the code, run

gulp serve

#2. Inject react.js

bower install react --save

Now you have react.js on your home page.

#3. Reactify JSX files

npm install reactify --save-dev

I have just published a blog on codepen. If you are an AngularJs developer and wonder if you should give ReactJs a try, check it out.

Mock has become so popular in agile development teams. Many disciplined teams won’t write a unit test without mocked dependencies. However, mock is not the silver-bullet. Instead, I find many teams using mock struggle with refactoring. Martin Fowler, Kent Beck and David David Heinemeier Hansson had a hangout last year, in which the shared their opinions on mocking.

The substantial problem of mocking is that when you set up the dependencies with mock, you are assuming an implementation, because you know that the mocked method will be called.

Martin Fowler, Kent Beck and David Heinemeier Hansson had a hangout talking about TDD, in which all three expressed their concerns around mocking from different angles. The videos last for more than one hour so here is the text version if you prefer. The hangout is not just about mocking. So I have attempted to summarise their concerns or comments on mocking below (extracted from the text version):

  • David Heinemeier Hansson does not agree with “isolated unit testing” because there tend to be “lots of mocks”.
  • Kent Beck doesn’t mock very much; implies it’s a smell of bad design.
  • Martin Fowler doesn’t mock much either.

DHH, Kent Beck and Martin Fowler did not use any code example in their hangout. I think some Java code can demonstrate the real problems better.

Let’s use online store as an example. To summarise the business rule, if an Order is shipped to within Australia, free shipping is applied, otherwise no free shipping.

Here is our test code:

@Test
public void free_shipping_applies_on_orders_shipped_within_australia(){
    Country mockedCountry = mock(Country.class);
    when(mockedCountry.getName()).thenReturn("Australia");

    Order order = new Order(mockedCountry, other, parameters);
    assertThat(order.freeShipping(), isTrue());
}

Here is our Order class under test:

public class Order {
    // other methods
    ......
    public boolean freeShipping() {
        return country.getName().equalsIgnoreCase("Australia");
    }
}

Now we would like to change the way to decide if the country is Australia from comparing Name to comparing Country Code.

public class Order {
    public boolean freeShipping() {
        return country.getCountryCode().equalsIgnoreCase("Au");
    }
}

The test will fail (throw NullPointerException), because getCountryCode is not mocked. We assumed that we will call getName, but that is an implementation detail. We are not changing the behaviour of the class Order. The test should pass without any change. If real Country object is used, it won’t fail. Yes, as you said, we should test contract. But we should test the contracts of the class that is under test, not how the class under test interacts with its dependencies, which is again implementation detail. A paper (www.jmock.org/oopsla2004.pdf ) published in 2004 suggested that we should “mock roles, not objects”. I agree that it is good technique to drive interfaces. It should be limited to that. It should not be used when the dependent classes are already there.

This is an elaborated example, but it does not mean the problems are there in rare cases. It is common and popular. I’ve seen more teams using Mock in most of the unit tests than not doing that. When they feel the pain of re factoring, they believe that is necessary pain. More teams do not feel the pain, because it has not hurt them that hard.

So I would like to reiterate the problems of mocking:

  1. Mocking is unfriendly to refactoring. The Mock-based test is highly coupled with the implementation.

  2. Mocking makes untestable (bad-designed) code look testable and gives fake confidence. Sometimes, especially when the object is quite complex, mocking an object is easier than creating a real object. That is a design smell(as Kent Beck said). It means your code violates either Single-Responsibility-Principle or Law of Demeter* or, in most cases, both. Before mocking your own classes, re-think if it is easy to create, build and configure. The team may lose an opportunity to verify the design, if they always go with mocking.

  • It is easy to understand, that when an object is difficult to create it may have too many dependencies and then tends to violate SRP. Another possible reason is it has a long dependency chain, thus difficult to create. In this case the code violates LoD.

Here be a sample post with a custom background image. To utilize this “feature” just add the following YAML to a post’s front matter.

image:
  background: filename.png

This little bit of YAML makes the assumption that your background image asset is in the /images folder. If you place it somewhere else or are hotlinking from the web, just include the full http(s):// URL. Either way you should have a background image that is tiled.

If you want to set a background image for the entire site just add background: filename.png to your _config.yml and BOOM — background images on every page!

Background images from Subtle Patterns (Subtle Patterns) / CC BY-SA 3.0

Implementing Accessibility with AgularJs

####This blog is written with love.

We have recently been using the Web Content Accessibiity Guidelines version 2.0 (WCAG 2.0) to improve the accessibility of our web projects.. In this blog, we will show a creative way to implement the item ARIA2: Identifying required fields with the aria-required property.

The following is a typical input field(input is a void element. the closing “/” is optional.):

<label for="user-name">User Name:</label>
<input id="user-name" type="text"/>

And in the browser, it looks like this in a browser:

text input with label

We would like to add asterisk to the label, if the input field is required:

required input field with label

The HTML element looks like:

<label for="user-name">User Name:<abbr title="required" class="required">*</abbr></label>
<input id="user-name" type="text"/>

There are many fields need to be updated, to make it simple, we are going to do it dynamically with angularjs.

Implementation

Directive asterisk

Let’s create a aterisk directive first.

//HTML

<asterisk></asterisk>

//JavaScript

// ua means usability and accessibility
var uaModule = angular.module('ua', []);

uaModule.directive('asterisk', function(){
  return {
    restrict: 'E', // only apply to Element
    template: '<abbr title="required" class="required"">*</abbr>',
    transclude: 'true',
    replace: 'true' // replace the current element
  }
});

Make sure you have bootstrapped your html with:

angular.element(document).ready(function () {
  angular.bootstrap(document, ['ua']);
});

Now whenever you add an asterisk element in your DOM structure, you will see a “*” on the page.

Please checkout this pluckr: http://plnkr.co/edit/kIIBicQklGuZVDblkw0Z?p=preview

Directive require

required is a new attribute introduced in HTML5, and is supported by all main stream browsers. Though there is a ‘html5shiv.js’ to fix some issue on IE9, I have NOT verified it. Please leave comments, if it does not work on your IE9 with html5shiv.

What we want to achive is have angularjs add the required span when it finds a required attribute on the input element.

First, add required attribute to input element. The code looks like:

<label for="user-name">User Name:</label>
<input id="user-name" type="text" required/>

After the enhancement, it will become:

<label for="user-name">User Name:
	<abbr title="required" class="required">*</abbr>
</label>
<input id="user-name" type="text" required/>
uaModule.directive('required', ['$document', '$compile', function (document, compile) {
  var linkFn, labelNode, labelElement, abbrElement;

  linkFn = function (scope, element, attrs) {
    // eliminate the dependency on jQuery
    labelNode = document[0].body.querySelector("label[for='" + attrs['id'] + "']");
    if (labelNode) {
      labelElement = angular.element(labelNode);
      // @ add asterisk to the label of a required input field
      abbrElement = angular.element('<asterisk/>');
      labelElement.append(compile(abbrElement)(scope));
    }
  };

  return {
    restrict: 'A',
    link: linkFn
  };
}]);

The final plnkr can be found here.