Wednesday, March 23, 2016

Sinon Tutorial: JavaScript Testing with Mocks, Spies & Stubs

This article was peer reviewed by Mark Brown and MarcTowler. Thanks to all of SitePoint's peer reviewers for making SitePoint content the best it can be!

One of the biggest stumbling blocks when writing unit tests is what to do when you have code that's non-trivial.

[author_more]

In real life projects, code often does all kinds of things that make testing hard. Ajax requests, timers, dates, accessing other browser features... or if you're using Node.js, databases are always fun, and so is network or file access.

All of these are hard to test because you can't control them in code. If you're using Ajax, you need a server to respond to the request, so as to make your tests pass. If you use setTimeout, your test will have to wait. With databases or networking, it's the same thing — you need a database with the correct data, or a network server.

Real-life isn't as easy as many testing tutorials make it look. But did you know there is a solution?

By using Sinon, we can make testing non-trivial code trivial!

Let's find out how.

What Makes Sinon so Important and Useful?

Put simply, Sinon allows you to replace the difficult parts of your tests with something that makes testing simple.

When testing a piece of code, you don't want to have it affected by anything outside the test. If something external affects a test, the test becomes much more complex and could fail randomly.

If you want to test code making an Ajax call, how can you do that? You need to run a server and make sure it gives the exact response needed for your test. It's complicated to set up, and makes writing and running unit tests difficult.

And what if your code depends on time? Let's say it waits one second before doing something. What now? You could use a setTimeout in your test to wait one second, but that makes the test slow. Imagine if the interval was longer, for example five minutes. I'm going to guess you probably don't want to wait five minutes each time you run your tests.

By using Sinon, we can take both of these issues (plus many others), and eliminate the complexity.

How Does Sinon Work?

Sinon helps eliminate complexity in tests by allowing you to easily create so called test-doubles.

Test-doubles are, like the name suggests, replacements for pieces of code used in your tests. Looking back at the Ajax example, instead of setting up a server, we would replace the Ajax call with a test-double. With the time example, we would use test-doubles to allow us to "travel forwards in time".

It may sound a bit weird, but the basic concept is simple. Because JavaScript is very dynamic, we can take any function and replace it with something else. Test-doubles just take this idea a little bit further. With Sinon, we can replace any JavaScript function with a test-double, which can then be configured to do a variety of things to make testing complex things simple.

Sinon splits test-doubles into three types:

  • Spies, which offer information about function calls, without affecting their behavior
  • Stubs, which are like spies, but completely replace the function. This makes it possible to make a stubbed function do whatever you like — throw an exception, return a specific value, etc
  • Mocks, which make replacing whole objects easier by combining both spies and stubs

In addition, Sinon also provides some other helpers, although these are outside the scope of this article:

With these features, Sinon allows you to solve all of the difficult problems external dependencies cause in your tests. If you learn the tricks for using Sinon effectively, you won't need any other tools.

Installing Sinon

First off we need to install Sinon.

For Node.js testing:

  1. Install Sinon via npm using npm install sinon
  2. Require Sinon in your test with var sinon = require('sinon');

For browser based testing:

  1. You can either install Sinon via npm with npm install sinon, use a CDN, or download it from Sinon's website
  2. Include sinon.js in your test runner page.

Getting Started

Sinon has a lot of functionality, but much of it builds on top of itself. You learn about one part, and you already know about the next one. This makes Sinon easy to use once you learn the basics and know what each different part does.

We usually need Sinon when our code calls a function which is giving us trouble.

With Ajax, it could be $.get or XMLHttpRequest. With time, the function might be setTimeout. With databases, it could be mongodb.findOne.

To make it easier to talk about this function, I'm going to call it the dependency. The function we are testing depends on the result of another function.

We can say, the basic use pattern with Sinon is to replace the problematic dependency with a test-double.

  • When testing Ajax, we replace XMLHttpRequest with a test-double which pretends to make an Ajax request
  • When testing time, we replace setTimeout with a pretend timer
  • When testing database access, we could replace mongodb.findOne with a test-double which immediately returns some fake data

Let's see how that works in practice.

Spies

Spies are the simplest part of Sinon, and other functionality builds on top of them.

The primary use for spies is to gather information about function calls. You can also use them to help verify things, such as whether a function was called or not.

var spy = sinon.spy();

//We can call a spy like a function
spy('Hello', 'World');

//Now we can get information about the call
console.log(spy.firstCall.args); //output: ['Hello', 'World']

The function sinon.spy returns a Spy object, which can be called like a function, but also contains properties with information on any calls made to it. In the example above, the firstCall property has information about the first call, such as firstCall.args which is the list of arguments passed.

Although you can create anonymous spies as above by calling sinon.spy with no parameters, a more common pattern is to replace another function with a spy.

var user = {
  ...
  setName: function(name){
    this.name = name;
  }
}

//Create a spy for the setName function
var setNameSpy = sinon.spy(user, 'setName');

//Now, any time we call the function, the spy logs information about it
user.setName('Darth Vader');

//Which we can see by looking at the spy object
console.log(setNameSpy.callCount); //output: 1

//Important final step - remove the spy
setNameSpy.restore();

Replacing another function with a spy works similarly to the previous example, with one important difference: When you've finished using the spy, it's important to remember to restore the original function, as in the last line of the example above. Without this your tests may misbehave.

Spies have a lot of different properties, which provide different information on how they were used. Sinon's spy documentation has a comprehensive list of all available options.

In practice, you might not use spies very often. You're more likely to need a stub, but spies can be convenient for example to verify a callback was called:

function myFunction(condition, callback){
  if(condition){
    callback();
  }
}

describe('myFunction', function() {
  it('should call the callback function', function() {
    var callback = sinon.spy();

    myFunction(true, callback);

    assert(callback.calledOnce);
  });
});

Continue reading %Sinon Tutorial: JavaScript Testing with Mocks, Spies & Stubs%


by Jani Hartikainen via SitePoint

How to Migrate a WordPress Site to a New Domain and Hosting

Even though moving your WordPress site to a new host can be a bit stressful, if it is not done properly it can result to some annoying and unexpected errors. The truth is, if it is well handled, it should be a stress free experience.

In this tutorial, I will be showing you how you can properly move your WordPress site to both a new host and also to a new domain, without having to face any of the common problems that arise with migrations.

Deactivate All Plugins

Before you begin, I’d recommend that you deactivate all plugins because, when moving a WordPress site to a new host, the things that are likely to fail are your WordPress plugins. WordPress itself is well programmed to adapt to new changes, but the plugins might not.

Continue reading %How to Migrate a WordPress Site to a New Domain and Hosting%


by Doyin Faith Kasumu via SitePoint

How Good Are Your HTML and CSS Comments?

One of the things you usually learn when you start learning about basic HTML or CSS is how to write comments in your code. However, many web developers still don’t use comments to their advantage. We may use comments widely in HTML and CSS, but when written properly, and with intent, they can really improve our workflow.

When you start working at a new company, looking at manuals or many pages of documentation can be daunting. Every company is different – meaning that the codebases, amount of legacy code, development of frameworks, and amount of modular code can be different.

We’re often told that "good code doesn’t need comments", but do you ever find yourself going around in circles, completely lost, and searching for documentation because of a lack of comments?

Two Facts About Code Comments

  1. Comments are ignored by the browser.
  2. Comments are stripped out during minification.

Based on these two facts, we know that comments are not really meant for machines – they are meant for humans to read.

Why Commenting Code Is Important

When you are freelancing and working on a solo project, or when you are the only developer who is going to be looking at your code, it’s easy to go about it your own way and make comments as you see fit, or maybe leave no comments at all. But a lot of the time, developers say that they look back at their own code and wonder, "What was I thinking?" or struggle to understand that code they have written.

Comments can help maintain consistency. If you have consistent, well-written comments for what you are building then you are more likely to build things the same way each time.

Comments facilitate understanding. This is really important in a team where sometimes one person does not do all the work. You might write comments to help yourself figure out some logic, and even though you do not keep all of your comments by the end of the project, it can help you better understand how you came to a solution. It can help you improve on that solution much more easily later on.

Commenting can also assist with hotfixes or quick fixes. Comments can actually help in three ways here. They can help developers understand the code if they need to make a quick fix (especially developers outside of the front-end team who may be helping out), it can help by marking out where these fixes are needed, and can show where quick fixes have been applied and need to be removed at some point.

Comments help speed up the development process. You can have a clearer understanding of what you are creating, changing or removing if you include relevant comments.

Comments facilitate more efficient collaboration. If you know the ins and outs of a project or codebase, you are more likely to get bits and pieces done quicker, thus improving workflows.

Comments help a lot of people. They not only help yourself, but they can help other people in your team. Gone are the days that we saw comments like DO NOT STEAL MY CODE in people’s source code. While we used to be very protective of our code, not wanting to share our ‘secrets’, we now live in a world where people share code, work on projects together and collaborate. We are not ashamed of crediting the likes of Harry Roberts, Chris Coyier or Jonathan Snook when it comes to web projects. With this shift in collaboration, we should also take note of our commenting practices – and help our peers.

Some Things to Avoid When It Comes to Comments

Avoid Commenting Absolutely Everything

It may be tempting to get into the habit of commenting every block of code, but this can be more redundant than useful or helpful. Commenting should only be done where something may not be completely clear. If you considered semantics when naming your classes, your code may already be easy to understand.

This may also be where the concept of "good code does not need comments" came from. Comments should not be completely avoided, but only used where necessary.

Do Not Be Too Verbose

I am personally guilty of writing some rather long comments in my CSS, because I love explaining and documenting things. However, you shouldn’t be writing novels – long comments are as much a pain to read as they can be to write. If you can be succinct, do so. Sometimes, when naming CSS classes, the following advice is given:

Make class names as short as possible but as long as necessary.

The same applies to comments. It’s good to read over any comments you write to ensure that you understand them yourself. Imagine you are someone new to the code and you are reading the comments as a guide.

Do Not Spend Too Much Time Writing Comments

I once saw a file in a project I was working on that had a line at the top reading:

[code language="sass"]
// Update this with how many hours you have spent on this file:
// TIME_WASTED = 438;
[/code]

You shouldn’t need to spend a lot of time writing comments. A few words is usually enough. If you are spending too much time trying to comment your code to make sure someone else will understand it, consider that parts of your code might actually need refactoring.

Some Examples of When to Use Comments

To Explain a Pseudo Element's Purpose

This example shows a pseudo element with the content value filled in.

[code language="css"]
.post__comment-container::after {
background-color: #f9f9f9;
border: 1px solid #dedede;
border-radius: 0.25em;
color: #888;
content: 'Post author';
display: inline-block;
font-size: 0.7rem;
margin-left: 0.5rem;
padding: 0.2rem 0.45rem;
vertical-align: middle;
}
[/code]

It may not be immediately clear what a pseudo element is for, especially if the content property is displayed as content: ''. With a short comment above the code block, we can improve this.

[code language="css"]
/* Post author label for comment */

.post__comment-container::after {
background-color: #f9f9f9;
border: 1px solid #dedede;
border-radius: 0.25em;
color: #888;
content: 'Post author';
display: inline-block;
font-size: 0.7rem;
margin-left: 0.5rem;
padding: 0.2rem 0.45rem;
vertical-align: middle;
}
[/code]

Continue reading %How Good Are Your HTML and CSS Comments?%


by Georgie Luhur via SitePoint

Filterizr – Custom Filters for Responsive Galleries

Filterizr is a jQuery plugin that sorts, shuffles and applies stunning filters over responsive galleries using CSS3 transitions.


by via jQuery-Plugins.net RSS Feed

James Gillen Portfolio

The portfolio of designer James Gillen working across digital, print and branding.


by csreladm via CSSREEL | CSS Website Awards | World best websites | website design awards | CSS Gallery

artmark Gallery

Websitefor the great vienna Art gallery.


by csreladm via CSSREEL | CSS Website Awards | World best websites | website design awards | CSS Gallery

Pantazis Fruits

Pantazis fruits S.A. is a company with more than 54 product codes of fruit and vegetables from all over Greece and exports to 34 countries worldwide.


by csreladm via CSSREEL | CSS Website Awards | World best websites | website design awards | CSS Gallery