Unit Testing Self-Invoking JavaScript Functions

When Akanoo started out, we only tested our components run on Java – either written in Scala or using Grails or Groovy – with JUnit, ScalaTest and Spock. By the end of 2015 we also wanted unit tests for our JavaScript tracking library that is integrated in our client’s online shops.

Finding the right test framework

Nobody in our team had experience in testing JavaScript, so I went out looking for JavaScript unit test frameworks. What does one do if one has no clue? Google, of course. The first hit was QUnit developed and used by the jQuery team. I looked into other libraries but decided to give QUnit a shot. The reasons I chose it were:

  • Support by the community (In this case the jQuery community.)
  • Used by some big players (jQuery certainly is a big player.)
  • Easy to use (Check out the cookbook.)
  • Easy to understand for Java-developers (Hence, similarity with JUnit.)
  • Plug-in support & availability of plug-ins (We’ll come to this later.)

So, I had chosen my test framework. Let’s write some tests.

Testing self-invoking JavaScript Functions

Well, testing wasn’t that easy at the beginning. Our tracking script is encapsulated in a self-invoking function also known as immediately-invoked function expression (IIFE). The reason behind is to avoid polluting the global space (everything in the window object) with our functions and variables and only allow access via our API calls using the exposed function at(). See an example of an immediately-invoked function expression below:

<script>
(function(a, b) {
  // our tracking code goes here
  var foo = "bar";
  
  function bla() {
    // sample function
    console.log(foo);
  }
})(window, document);
</script>

As the name says, the function is immediately invoked after definition and I have no chance to call the function itself or to access the variables and functions inside. What could I do to test the function bla() in the above example?
My first idea was to comment out the two lines that define the function as self-invoking and define the parameterized variables by hand:

<script>
var a = window, b = document;//(function(a, b) {
  // our tracking code goes here
  var foo = "bar";
  
  function bla() {
    // sample function
    console.log(foo);
  }
//})(window, document);
</script>

I am now able to call the function bla() and access the variable foo. So I went over to my test files and wrote some QUnit tests.

Spying with Sinon.js

Once I finished writing some easy test checking for the output of functions with various input parameters. Unfortunately, some functions are called inside other functions and these make for harder testing. If I want to know whether the inner function has been called, I need to spy on its execution.

<script>
function A() {
  B();
}

function B() {
  // do something
}

A();
</script>

QUnit itself doesn’t offer functions for spying, so I googled again to find a solution for JavaScript “mocking” [https://en.wikipedia.org/wiki/Mock_object]. I stumbled upon Sinon.js [http://sinonjs.org/] which offers spies, stubs and some more nifty features and integrates nicely with QUnit.

I started to write some tests but the function sinon.spy(object, “function”) requires to specify the encapsulating object of the “function” to spy. After my changes to the self-invoking function expression the functions reside in the “global” scope which in JavaScript means they lie under the window object.

// the following line will be replaced by the code in the comment
var a = window, b = document;//(function(a, b) {
  // our tracking code goes here
  var obj = {
    // variables go here
    foo: "bar";
  }
  
  // functions go like this
  obj.bla = function() {
    // sample function
    console.log(foo);
  }
//})(window, document);

Unfortunately, I wasn’t able to spy functions using Sinon on the window object. So, I went on putting all functions inside my faked IIFE inside an object to make them testable. Of course, I had to refactor the existing code already to some extent, i.e. extracting functions, avoiding anonymous functions etc. I strongly recommend to use JSHint.

Notice: When asserting spies with Sinon’s function withArgs(arg0, arg1, …) be aware that the order of arguments must be the same as in the call. If you want to check for the first two of three arguments, you may omit the third but if you want to check for the latter ones, the first argument needs to be defined.

Stubbing with Sinon.js

Sometimes the result of function A is dependent on the result of function B that is called inside function A. To test, I have to manipulate the inner function B to always return a predefined value. This is called stubbing and can be done with Sinon.js by calling sinon.stub(object, “function”).
You should also check out the faked XHR and faked server that Sinon offers. They were very helpful for my unit tests.

Conclusion

If you’ve read until now you certainly can guess that it was a long way down the road to 95% test coverage (measured with JSCover). The upsides of this solution using QUnit and Sinon.js is apparently that we achieved the possibility of unit testing. The obvious downside is the superfluous object in the IIFE. That is, however, not so bad as the Google closure compiler with hard optimization enabled minifies the code efficiently.

Meet our new Sales Manager Malte

Malte has joined our team in January as a Sales Manager. In his interview, he will tell you more about his passion for sales and business development.

What have you done before joining us?

Except a handful of internships, I haven’t done a job for a long term yet . Last year I established the company ‘die Herren Edel GmbH’, where I work as CEO. Also, I am still studying economy engineering at University of Hamburg, looking forward to graduate next year.

What are your responsibilities at Akanoo?

At Akanoo, I am part of the sales team and acquire customers to increase the revenue.

What do you enjoy most about your work?

Again and again, I get the chance, to convince managers to first: Talk with me for some minutes and second: To take 30 minutes for a presentation. It’s a challenging task, and I like the feeling when it works, the feeling to know that I am able to talk straight to managers in high positions.

And what do you usually do after work?

For me, after work is before work. I have some other projects, especially my own company, but also business ideas that I am developing. I am a businessman by heart. That’s why I actually won’t call it work – it’s my passion. Also I am doing Bikram Yoga for my health and my soul and I read a lot, mostly biographies other non-fiction books.

Which colleague would you take with you to a lonely island and why?

I would take Fabian, because he has similar interests as I have, so I guess talking to him and trying to create something new and build some practical things at the island would be much fun, even if we can’t help people with it or  sell it

Which attraction/part of Hamburg do you think you should definitely visit and why?

I like the chocoversum, a chocolate museum. It’s yummy and interesting at the same time. :-)

Which apps could you never do without and why?

The HVV app, because I would always miss trains and buses and annoy everyone of my friends, being too late.

These blogs/websites belong to my daily reading:

www.dieherrenedel.de

On the web you can find me here:

Xing

Top 4 Akanoo Name Twins

Ever wondered where our name Akanoo came from? Our name “Akanoo” originates from the Maori language. It means to “persuade” or “create” and thus fits perfectly to our Predictive Analytics solutions.

But, we are not the only ones, who think it is a great name. Here are our Top 4 name twins:

1. Akanoo, the Rapper

In the music business names are almost as important as sound. We have a name twin who is active in the rapper scene:

2. Akano Animee Artist

Apart from Hip Hop, we have a name twin, who performs anime songs and does some vocaloid.

3. Material Arts Fighter Akano

Furthermore, we have a name twin, who is a professional Material Arts Fighter from Japan.

4. Educational Channel Akanoo cc

In education, our name is popular, too. Akanoo cc is an educational YouTube channel from Bahrain, that is streaming conferences and music performances.

Akanoo Christmas campaign for a good cause

„Let’s make a difference together. You choose, we pay!“ – With this slogan, we have asked our clients and partners to participate in our Christmas campaign. Until the 13th January the companies could redeem a code they had received with Christmas cards. They could choose one of four charity organisations that would then receive our donation amounting to 10€ per participant. Clients and partners could choose between:

We sent our Christmas cards to German (81%), English (13%) and French (5%) clients and partners. In total 31% responded to the Christmas campaign. 90% of the respondents were German, 6% French and 4% English-speaking.

Most of the companies chose the charity MSF (58%), followed by UNHCR and DGzRS both with 15% and Arbeiterkind with 12%. The following chart gives an overview of our campaign results:

Thank you to all our clients and partners for participating in our Christmas campaign and helping us in giving something back.

Akanoo joins the Digital Advisory Board Summit

We are happy to announce our participation in the Digital Advisory Board Summit on February 1st 2017. At the summit, digital leaders and experts come together to discuss challenges and solutions for Digital Transformation.

Akanoo is one of six high-tech startups from the digital domain that will attend the summit to provide an indepth view from the frontier of digital transformation to large corporations and industry giants. We are very proud that the nextMedia.Hamburg competition selected us to contribute valuable insight during the summit.

We thank nextMedia.Hamburg for giving us the opportunity to participate in the summit. We are looking forward to interesting discussions about Digital Transformation.

Meet our new Data Scientist Torge

Torge is supporting the Data Science team since December. To give you an impression of him and his responsibilities we asked him to answer the Akanoo team member questionnaire:

What have you done before joining us?

I worked for a few years at Hamburg University of Technology as a research assistant where I wrote my Phd thesis in mathematics.

What are your responsibilities at Akanoo?

I am a Data Scientist and as such it is my responsibility to answer data-related questions and develop/improve our statistical model.

What do you enjoy most about your work?

Besides having great colleagues I enjoy being able to apply my knowledge as a mathematician.

And what do you usually do after work?

After work I usually take a long trip to Stade, where I currently live.

Which colleague would you take with you to a lonely island and why?

Sven, since he is the oldest and wisest of us all.

Which attraction/part of Hamburg do you think you should definitely visit and why?

The new Elbphilharmonie, since I am anxious to see what the acoustics are like.

Which apps could you never do without and why?

Threema and Netflix. I use Threema to communicate and Netflix as a remote for the TV.

These blogs/websites belong to my daily reading:

Currently Reddit.

Christmas shoppers behaviour differs in online shop industry

anatomie-des-onlineshoppers-adaptions-5The closer Christmas is coming, the more people shop online. We don’t share a secret telling you that Christmas is the most lucrative time of the year. We asked how many additional visitors and revenue online shops really generate during the Christmas season.

Traffic increase for all branches

Our Akanoo Data Insights tool provides relevant benchmarks for online retailers to evaluate the performance of their shops and enables us, to dive deep into the Christmas season and the performances of different branches. A comparison of the yearly average with the figures of December clearly shows that many online shops have a significantly higher amount of shop visitors. On average, online shops show a traffic increase of 123.0%.

Thus, a closer look at different industries like fashion, DIY and consumer goods shows that the traffic increase differs between the different portfolios. In the fashion segment the traffic amount climbs up by 97.1 %. DIY shops show a rise of 112.2% in visits. Compared to fashion and DIY can shops increase their visits with consumer goods by remarkable additional 169.4% visitors.

Conversion increase differs massively

While higher traffic is often going with weaker conversion rates, the additional Christmas traffic shows even a higher conversion rate. On average, the conversion rate increases by 15.4 % during the Christmas season. Comparing fashion, DIY and consumption we recognize the following: Fashion online shops create 4% more conversions in the Christmas season. Shops which offer consumer goods show an increase of 8%. DIY shops are one of the segments which realise double-digit growth of 14.3 % in conversions.

Our benchmark shows the enormous potential for online shops to generate additional revenue. In order to make the best use of the Christmas traffic, it is necessary to evaluate permanently the shop performance and to compare it to industry and product benchmarks.

We support you in identifying the best optimisation areas for your online shop. Contact us today.

 

Meet our new Sales Manager Gwen

gwen_emplyoee_interview

We are happy to welcome Gwen as part of our Sales Team. To give you an impression of her and to show you how she convinced us to work together, we asked her to answer our questionnaire for new team members.

What have you done before joining us?

I worked for a online marketing and print company (that doesn’t exist anymore) and in two online games companies as online marketing and sales manager for France.

What are your responsibilities at Akanoo?

Acquiring new customers for the French market and account management for existing customers.

What do you enjoy most about your work?

Being in contact with people.

And what do you usually do after work?

Take care of my two kids.

Which colleague would you take with you to a lonely island and why?

Everybody or nobody! And as long as I’m the only full-time woman here at the moment (and being French), it would be way too tendentious!

Which attraction/part of Hamburg do you think you should definitely visit and why?

The old city center because of its history and the French crêperie. :)

Which apps could you never do without and why?

Google maps, for obvious reasons!

These blogs/websites belong to my daily reading:

On the web you can find me here:

New customers for Akanoo Onsite Marketing: Thalia and Corsair

blost-new-customer-corsair-thalia

We are happy to announce the collaboration for our Automated Onsite Marketing with Thalia and Corsair, two well-known brands in the German and French market.

Thalia is one of the biggest retailers for books in the German-speaking market. Thalia’s online shop invites customers’ to choose from a huge variety of books and other entertainment products like audio CDs, video games and toys.

Corsair is a French company specialized in international long-haul flights. Each year, nearly 1.3 million passengers travel on Corsair lines worldwide. On its online shop visitors can book flights and additional holiday-related services like rental cars or hostel rooms.

We are looking forward to a lot successful campaigns with our new clients Thalia and Corsair.