Tag Archives: Web Design

PHP LOGIN SYSTEM RELOADED V1.1

Here’s an updated version of the PHP Login System. You can check the old version here. The following was added: 1. Registration fields: email confirmation password confirmation country recaptcha Email confirmation and password confirmation are configurable fields. By default they are shown, but if you wish to remove one or both of them you have …

Here’s an updated version of the PHP Login System.

The following was added:

1. Registration fields:

  • email confirmation
  • password confirmation
  • country
  • recaptcha

Email confirmation and password confirmation are configurable fields. By default they are shown, but if you wish to remove one or both of them you have to set it in the file constants.php:

define("REPEAT_EMAIL",true);
define("REPEAT_PASSWORD",true);

2. Table fields:

  • the user ip,
  • number of logins of a user,
  • flag is_admin
  • flag is_blocked
  • new table – Country table

3. dbcontroller class sanitizes user input data

4. Edit Account Area

5. Admin Area – incomplete (for next version)

For now just the list of users is shown and a world map indicating where the users come from.  You can delete Users and set them as Admins. If there are no users to list, no map is shown. Also the User seeing the panel is not shown.
Note that in the demo you will not be able to see the admin part – for admin reasons :)

6. New CSS

7. Some other small details in the php code.

For the next version I am planning to :

  • add all admin functions
  • improve and improve ….

To use the recaptcha you need to get a public/private key . Then you need to define them in constants.php:

define("PUBLICKEY","XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
define("PRIVATEKEY","XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");

In order to use the demo for those who have registered in the previous version’s demo, you need to register again (in the demo login system), since I had to set up another database for it.

Hope you like it. Any suggestions or improvements are welcome!

How Grunt Can Improve WordPress Development

In the first part of this series I gave a quick overview of Grunt. I also talked through the different technologies that it requires in order to use. After that, I got a little into the Gruntfile and the tasks inside of it.

Now I want to talk about how using Grunt can improve your development for both WordPress themes and plugins.

Easy Project Setup

My favorite part about using Grunt and npm is that as you set up your project, it is self-documenting your project’s dependencies. This is great for development teams and open-source projects. Who want’s to write documentation on how to setup a workspace anyway, right?

package.json

First, you will need to have a package.json file in your project. You will need to have the project’s name, version, and description set up. We will get into more detail around this in the next post, but here’s an example:

{
"name": "project-name",
"version": "1.0.0",
"description": "Awesome project"

}

Once you have this set up, when you install a grunt plugin, you just need to append --save-dev to the end and it will add the plugin to your package.json file underdevDependencies. For instance, if I wanted to add the grunt-contrib-watch plugin to my project I would run the following command:

npm install grunt-contrib-watch --save-dev

You will see the plugin added to your  node_modules folder and it should also result in your package.json file to look like this:

{
"name": "project-name",
"version": "1.0.0",
"description": "Awesome project",
    "devDependencies": {
"grunt-contrib-watch": "~0.5.x"
}
}

As you install other Grunt plugins and add --save-dev to the end, you will see them added under the devDependencies object.

npm install

Why is this beneficial? Like I mentioned earlier, this is self documenting your projects dependencies. Once you get all your plugins installed and added to your package.json file, now another team member or contributor can run npm install and they will install everything needed for the project.

You can test this out pretty easily by deleting your entire node_modules  folder and running npm install yourself. You will see everything you setup installed automatically.

[note]You will want to add the node_modules folder to your .gitignore file so you don’t bloat your repository.[/note]

Watch For Changes

I use a lot of similar Grunt plugins with each project, but the one that I always install is the one I referenced before, grunt-contrib-watch. This plugin when executed will watch your project’s files and will kick off any tasks you have specified for that file or file type.

One example would be for any of your JavaScript files. When you make changes to one of them and save it, then you can have Grunt run a JSLint, concat, and minify task. You can specify an order as well, so when one succeeds, the next gets kicked off. If one fails, then it kills the entire task sequence.

CodeKit has a similar feature, but it runs all of your tasks. For instance, if you make a change to a SASS or LESS file, it not only kicks off those tasks, but it also kicks off your JavaScript file tasks as well. The Grunt watch task gives you more control over what tasks run when specific files or file types are changed.

Creating Custom Tasks

Along with the Grunt tasks for the plugins you install, you can create your own custom tasks. A lot of times when I set up a project I have 3 tasks that I setup, default,setup, and build.

Default

The default task is the task that will run with you execute grunt from the command line. A lot of times I will map my watch task to default. You can add whatever task you want to run as well.

Setup

The setup task that I setup usually does the things that only need to happen the first time to set your project setup. A lot of times I use Bower to load third party libraries likeBootstrap and need to pull those down then run a copy task to move some files into my project and then kick off an initial compile of the LESS and JavaScript files.

Build

The build task is used for the things needed to be done before releasing or distributing your project. I always run this to make sure that everything is concatenated, minified and compressed. A great example is running grunt-contrib-imagemin to optimize all of the images in your project. Another example is using the grunt-contrib-compress to create a zip file of your theme so it’s easy to install via the WordPress admin.

Conclusion

Grunt is definitely a great tool for teams of developers. From automatically documenting your project’s dependencies to building custom, Grunt makes you efficient. Use Grunt to automate different tasks in your project so you can focus on building your WordPress theme or plugin.

Resources

Taxonomy Archives: List Posts by Taxonomy’s Terms

Final product image

What You’ll Be Creating

By default, WordPress creates archives which list all of your posts in reverse order. If users are looking for posts in a certain category or with a given taxonomy term, they’ll have to visit the archive page for that category or term.

But what if you want to make your main archive for a post type more user-friendly? In this tutorial, I’ll show you how to create an archive page for a custom post type which displays posts of that post type categorized according to a taxonomy, so that instead of one long list visitors will see a list for each taxonomy term.

What You’ll Need

To follow this tutorial you’ll need a development installation of WordPress and a code editor. You’ll be creating a theme which is a child theme of twentyfourteen, so you’ll need that installed (which it should be by default).

I’m not going to show you how to create a child theme, but if you’re stuck, just have a look at the stylesheet in the code bundle for this tutorial.

1. Getting Started: Registering the Post Type and Taxonomy

In my experience this technique is most commonly needed for custom post types and taxonomies rather than for normal posts and categories or tags, so I’ll start by registering a post type and taxonomy.

Note: I’m using the same ‘animal’ post type that I registered in an earlier tutorial oncreating an image-based archive. If you want to push things a bit further, you could combine the technique in that tutorial with the one I’m showing you here and display your taxonomy term lists with featured images.

In your theme’s functions file, add the following code to register the post type:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// register a custom post type called 'animals'
function wptp_create_post_type() {
    $labels = array(
        'name' => __( 'Animals' ),
        'singular_name' => __( 'animal' ),
        'add_new' => __( 'New animal' ),
        'add_new_item' => __( 'Add New animal' ),
        'edit_item' => __( 'Edit animal' ),
        'new_item' => __( 'New animal' ),
        'view_item' => __( 'View animal' ),
        'search_items' => __( 'Search animals' ),
        'not_found' =>  __( 'No animals Found' ),
        'not_found_in_trash' => __( 'No animals found in Trash' ),
    );
    $args = array(
        'labels' => $labels,
        'has_archive' => true,
        'public' => true,
        'hierarchical' => false,
        'supports' => array(
            'title',
            'editor',
            'excerpt',
            'custom-fields',
            'thumbnail',
            'page-attributes'
        ),
        'taxonomies' => array( 'post_tag', 'category'),
    );
    register_post_type( 'animal', $args );
}
add_action( 'init', 'wptp_create_post_type' );

Next, add the code to register the taxonomy:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// register a taxonomy called 'Animal Family'
function wptp_register_taxonomy() {
    register_taxonomy( 'animal_cat', 'animal',
        array(
            'labels' => array(
                'name'              => 'Animal Families',
                'singular_name'     => 'Animal Family',
                'search_items'      => 'Search Animal Families',
                'all_items'         => 'All Animal Families',
                'edit_item'         => 'Edit Animal Families',
                'update_item'       => 'Update Animal Family',
                'add_new_item'      => 'Add New Animal Family',
                'new_item_name'     => 'New Animal Family Name',
                'menu_name'         => 'Animal Family',
            ),
            'hierarchical' => true,
            'sort' => true,
            'args' => array( 'orderby' => 'term_order' ),
            'rewrite' => array( 'slug' => 'animal-family' ),
            'show_admin_column' => true
        )
    );
}
add_action( 'init', 'wptp_register_taxonomy' );

Once you’ve done this, add some data. Below you can see the data I’ve added with some taxonomy terms applied. I don’t make any claim for the accuracy of my terminology with regard to animal families, so please don’t comment if I’ve got that wrong!

2. Setting Up the Archive Template

The next step is to create an archive template for the new post type. In your theme, create a new file called archive-animal.php.

As this theme is a child theme of twentyfourteen, the archive template will need code copied from that theme as a wrapper for the custom loop you’re going to create. So add the following to your archive template:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php
/*
WpTutsPlus tutorial for creating archive to display posts by taxonomy term
Archive template for animal custom post type
*/
?>
<?php get_header(); ?>
    <div id="main-content" class="main-content">
    <div id="primary" class="content-area">
        <div id="content" class="site-content" role="main">
            <header class="archive-header">
                <h1 class="archive-title">
                    <?php post_type_archive_title(); ?>
                </h1>
            </header><!-- .archive-header -->
            
                        
        </div><!-- #content -->
    </div><!-- #primary -->
    <?php get_sidebar( 'content' ); ?>
</div><!-- #main-content -->
<?php
get_sidebar();
get_footer();

Note: If you’re working with your own theme, copy the wrapping code from your own theme’s index or archive file.

3. Populating the Archive Template: Fetching Taxonomy Terms

So that your archive can display animals by taxonomy term, the next step is to fetch those terms.

In your new template file, below the closing </header> tag (or below the opening part of your wrapping code if you’re using your own theme), fetch the terms usingget_terms():

1
2
3
4
5
6
<?php //start by fetching the terms for the animal_cat taxonomy
$terms = get_terms( 'animal_cat', array(
    'orderby'    => 'count',
    'hide_empty' => 0
) );
?>

Note that I’ve used two parameters here:

  • orderby – this allows you to specify the order of the terms displayed. I’ve usedcount as the value so that the term with the most posts assigned to it will be displayed first, but you could order by name or  ID – if you leave this blank, WordPress will order by name. See the Codex page on get_terms() for more details.
  • hide_empty – this tells WordPress not to fetch any terms without posts assigned to them. It saves you having to check if your query has any posts later on.

4. Populating the Archive Template: Defining the Query

Having done this, you use foreach() to tell WordPress to pass through each of these terms and run a query which you need to define. Below the code you just added, insert the following:

01
02
03
04
05
06
07
08
09
10
11
12
<?php
// now run a query for each animal family
foreach( $terms as $term ) {
    // Define the query
    $args = array(
        'post_type' => 'animal',
        'animal_cat' => $term->slug
    );
    $query = new WP_Query( $args );
    
}

This tells WordPress to run through each term, and then defines the query it has to run each time. The arguments for the query include the post type and the term in the'animal_cat' taxonomy, which is the value of the $term variable.

5. Populating the Archive Template: Adding a Loop

Having defined your query, you need to add a loop. First, output the name of the term being queried as a heading. Below the line beginning $query but inside the braces of the foreach statement, add this line:

1
echo'<h2>' . $term->name . '</h2>';

Next, add the code to contain your posts in a list:

1
2
3
4
// output the post titles in a list
echo '<ul>';
echo '</ul>';

Inside the list, now add your loop:

1
2
3
4
5
6
7
8
// Start the Loop
while ( $query->have_posts() ) : $query->the_post(); ?>
<li class="animal-listing" id="post-<?php the_ID(); ?>">
    <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endwhile;

As you can see , this is a straightforward loop which outputs the title of each post inside a link to the post, and doesn’t output any content. If you wanted you could add an excerpt or featured image here.

Finally, reset the query using wp_reset_postdata() below the line reading echo '</ul>';

The Whole Loop

This is what your query and loop will now look like:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?php
// now run a query for each animal family
foreach( $terms as $term ) {
    // Define the query
    $args = array(
        'post_type' => 'animal',
        'animal_cat' => $term->slug
    );
    $query = new WP_Query( $args );
            
    // output the term name in a heading tag               
    echo'<h2>' . $term->name . '</h2>';
    
    // output the post titles in a list
    echo '<ul>';
    
        // Start the Loop
        while ( $query->have_posts() ) : $query->the_post(); ?>
        <li class="animal-listing" id="post-<?php the_ID(); ?>">
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        </li>
        
        <?php endwhile;
    
    echo '</ul>';
    
    // use reset postdata to restore orginal query
    wp_reset_postdata();
} ?>

Finally, save your template file and view your post type archive. You’ll see that it lists your posts by taxonomy term rather than in one long list.

Summary

This technique is useful when you want visitors to be able to quickly see categorised data without having to look at a range of archive pages – it brings it all together in one place but sorted for convenience. Here are some ideas for how you could adapt the technique and take it further:

  • Call categories or tags instead of terms. To do this, you would useget_categories() or get_tags() .
  • Instead of creating a custom archive for a post type, use this technique in yourindex.php file to display posts by category, tag or taxonomy terms.
  • Instead of running one loop for each term, run two: the first one can display the most recent post with that term in full and the second one can display a list of all the rest of the posts. Use posts_per_page and offset in your query arguments to do this – see details of how this work on the WP_Query Codex page.
  • Use posts_per_page to limit the number of posts displayed so that each list is the same length. You could combine this with styling to display lists side by side.
  • For each term, add a link to the term archive page after the list of posts – this is particularly useful if you’re not displaying all of the posts in your list. Useget_term_link() to do this.

Don’t Forget to Cover Your Client Side!

By making sure that your application is tested, you are able to reduce the amount of bugs you find in your code, increase the maintainability of your application, and design well structured code.

Client side unit testing presents different challenges than server side testing. When dealing with client side code, you will find yourself struggling to separate application logic from DOM logic, as well as just structuring JavaScript code in general. Fortunately there are a lot of great client side testing libraries out there to help test your code, create metrics about the test coverage, as well as analyze the complexity of it.

Why Test at All?

First of all, unit testing in general is a way to reduce bugs by ensuring that your application functions as it’s supposed to. Beyond that though, are the notions of Test Driven Development (TDD) and Behavior Driven Development (BDD).

These two unit testing strategies will help you design your application by writing testsbefore you write your application logic. By writing the tests before you write the code, you’re giving yourself the opportunity to think through the design of your application.

This happens because when you’re writing tests, you’re basically trying to design the API for how you interact with your code, so you therefore get better insight into its design. Testing first will quickly show you any flaws you have in your design because you’re writing test code that essentially uses the code you’re writing!

TDD is a code discovery process

You’ll learn that TDD helps you discover your code as you’re writing it. TDD is summed up very quickly as “Red, Green, Refactor”. What this means is, you write a test, write enough code to make the test fail first. Then, you write the code that makes your test pass. After that, you think through what you just wrote and refactor it. Nice and easy.

BDD is a slightly different take on TDD and is based more on business requirements and specifications.

Client Side Testing

There are many reasons that you should be testing your client side code. As mentioned before, it will help reduce bugs, and help you design your application. Client side testing is also important because it gives you a chance to test your front end code, in isolation, away from your presentation. In other words, one of its advantages is you get to test your JavaScript code without actually spinning up an application server. You simply run the tests and make sure things function without clicking around and testing things. In many cases, you don’t even have to have internet access, as long as your tests are set up correctly.

With JavaScript taking such an important role in modern web development, it’s important to learn how to test code and reduce the chances of bugs making their way into production code. Your boss doesn’t like it when that happens and neither should you! In fact, a good place to get started working with client side testing is to write tests around a bug report. This will allow you to get practice writing tests when you don’t have a place to start from scratch.

Another reason to test your client side code is that once a suite of tests exists and has decent coverage over your code, when you get ready to go and add new features to your code, you’ll be able to add the new feature, re-run your tests, and make sure you didn’t regress and break any existing features.

Getting Started

Getting started with client side testing can be daunting if you’ve never done it before. One of the hardest parts about client side testing is figuring out the best way to isolate the DOM from your application’s logic. That often means you’ll need some sort of abstraction over the DOM. The easiest way to achieve this is through a client side framework such as Knockout.js, Backbone.js, or Angular.js, to name just a few.

When using a library such as these, you get to think less about how your page renders in the browser and more about the features of your application. It’s not like it’s impossible to unit test with just plain JavaScript though. In that case, your life will be much easier if you design the code in such a way that the DOM can easily be abstracted.

Choose a Testing Library

There are a lot of different testing libraries to choose from, although the three front runners tend to be QUnitMocha, and Jasmine.

Jasmine and Mocha are both from the BDD school of unit testing, whereas QUnit is just a unit testing framework of its own.

For the rest of this post, we’ll explore using QUnit as its barrier to entry in client side testing is very low. Check out this detailed intro to QUnit for more information.

TDD Your Code With QUnit

Getting started with QUnit is extremely simple. The following HTML is all you need:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>QUnit Example</title>
    <link rel="stylesheet" href="qunit.css">
</head>
<body>
    <div id="qunit"></div>
    <div id="qunit-fixture"></div>
    <script src="qunit.js"></script>
    <script src="../app/yourSourceCode.js"></script>
    <script src="tests.js"></script>
</body>
</html>

For the next few examples, let’s assume that we’re building a small widget that you input a zip code into a text box and it returns the corresponding city, state, and county values using Geonames. It’ll show only a zip code at first, but as soon as the zip code has five characters it’ll retrieve the data from Geonames. If it is able to find data, it will show a few more fields containing the resulting city, state, and county information. We’ll also be using Knockout.js. The first step is to write a failing test.

Thinking through the design slightly before the first test is written, there probably needs to be at least two viewModels, so that will be a good starting point. To start off, we’ll define a QUnit Module and our first test:

1
2
3
4
5
module("zip code retriever");
test("view models should exist", function() {
    ok(FormViewModel, "A viewModel for our form should exist");
    ok(AddressViewModel, "A viewModel for our address should exist");
});

If you run this test, it will fail, now you can go write the code to make it pass:

1
2
3
4
5
6
7
var AddressViewModel = function(options) {
};
var FormViewModel = function() {
    this.address = new AddressViewModel();
};

You’ll see green rather than red this time. Tests like this seem a bit silly at first, but they are useful in that they force you to at least think through some of the early stages of your design.

The next test we will write will work on the AddressViewModel‘s functionality. We know from the specification of this widget that the other fields should be hidden at first, until the data is found for the zip code.

01
02
03
04
05
06
07
08
09
10
11
12
13
module("address view model");
test("should show city state data if a zip code is found", function() {
    var address = new AddressViewModel();
    ok(!address.isLocated());
    address.zip(12345);
    address.city("foo");
    address.state("bar");
    address.county("bam");
    ok(address.isLocated());
});

None of the code for this has been written yet, but the idea here is that the isLocatedwill be a computed observable, that returns true only when the zip, city, state, and county are all truthy. So, this test will of course fail at first, now let’s write the code to make it pass.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
var AddressViewModel = function(options) {
    options = options || {};
    this.zip = ko.observable(options.zip);
    this.city = ko.observable(options.city);
    this.state = ko.observable(options.state);
    this.county = ko.observable(options.county);
    this.isLocated = ko.computed(function() {
        return this.city() && this.state() && this.county() && this.zip();
    }, this);
    this.initialize();
};

Now if you run the tests again, you’ll see green!

This is, at its most basic, how you can use TDD to write front end tests. Ideally, after each failing test, you’d write the simplest code that will make the test pass and then go back and refactor the code. You can learn a lot more about TDD practices though, so I suggest reading up and studying it further, but the previous examples are enough to get your mind thinking about writing tests first.

Mocking Dependencies With Sinon.js

Sinon.js is a JavaScript library that provides the ability to spy, stub, and mock JavaScript objects. When writing unit tests you want to make sure that you are able to test only a given “unit” of code. This oftentimes means you’ll have to do some sort of mocking or stubbing of dependencies to isolate the code being tested.

Sinon has an extremely simple API for doing this. The Geonames API supports retrieving data via a JSONP endpoint, which means we’ll be able to easily use $.ajax.

Ideally though, you won’t have to depend on the Geonames API in your tests. They could be down temporarily, your internet may die, and it also is just slower to actually make the ajax call. Sinon to the rescue.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
test("should only try to get data if there's 5 chars", function() {
    var address = new AddressViewModel();
    sinon.stub(jQuery, "ajax").returns({
        done: $.noop
    });
    address.zip(1234);
    ok(!jQuery.ajax.calledOnce);
    address.zip(12345);
    ok(jQuery.ajax.calledOnce);
    jQuery.ajax.restore();
});

Here in this test, we’re doing a few things. First of all, the sinon.stub function is actually going to proxy over jQuery.ajax and add the ability to see how many times it has been called, and many other assertions. As the test reads, “should only try to get data if there’s 5 chars“, we are going to assume that when the address is set to just “1234“, that no ajax call has been made yet, then set it to “12345“, and by that point an ajax call should be made.

We then need to restore jQuery.ajax to its original state, because we are good citizens of unit testing and want to keep our tests atomic. Keeping your tests atomic is important to ensure that one test does not depend on another test, and there’s no shared state between tests. They can then be ran in any order as well.

Now that the test is written, we can run it, watch it fail, and then write the code that performs the ajax request to Geonames.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
AddressViewModel.prototype.initialize = function() {
    this.zip.subscribe(this.zipChanged, this);
};
AddressViewModel.prototype.zipChanged = function(value) {
    if (value.toString().length === 5) {
        this.fetch(value);
    }
};
AddressViewModel.prototype.fetch = function(zip) {
    $.ajax({
        url: baseUrl,
        data: {
            "postalcode": zip,
            "country": "us"
        },
        type: "GET",
        dataType: "JSONP"
    }).done(this.fetched.bind(this));
};

Here we are subscribing to changes of the zip code. Whenever it changes, thezipChanged method will be called. The zipChanged method will check to see if the length of the value of the zip is 5. When it reaches 5, the fetch method will be called. Here is where the Sinon stub comes in to play. At this point, $.ajax is actually a Sinon stub. So calledOnce will then be true in the test.

The final test we’ll write is for when the data comes back from the Geonames service:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
test("should set city info based off search result", function() {
    var address = new AddressViewModel();
    address.fetched({
        postalcodes: [{
            adminCode1: "foo",
            adminName2: "bar",
            placeName: "bam"
        }]
    });
    equal(address.city(), "bam");
    equal(address.state(), "foo");
    equal(address.county(), "bar");
});

This test will test how the data from the server gets set onto the AddressViewmodel. Run it, see some red. Now make it green:

01
02
03
04
05
06
07
08
09
10
11
AddressViewModel.prototype.fetched = function(data) {
    var cityInfo;
    if (data.postalcodes && data.postalcodes.length === 1) {
        cityInfo = data.postalcodes[0];
        this.city(cityInfo.placeName);
        this.state(cityInfo.adminCode1);
        this.county(cityInfo.adminName2);
    }
};

The fetched method just makes sure there is an array of postalcodes in the data from the server, and then sets the corresponding properties on the viewModel.

See how easy this is now? Once you get the flow of doing this down, you’ll find yourself hardly ever wanting to not TDD again. You end up with nice small functions that are testable. You force yourself into thinking about how your code interacts with its dependencies. And now you have a suite of tests to run when some other new requirement is added to the code. Even if you miss something and there is a bug in the code, you are now able to simply add a new test to the suite, to prove that you’ve fixed the bug! It actually ends up being kind of addicting.

Test Coverage

Test coverage provides an easy way to evaluate how much of your code has been tested by a unit test. It’s often hard and not worth it to reach 100% coverage, but do what you can to get it as high as possible.

One of the newer and easier coverage libraries is called Blanket.js. Using it with QUnit is dead simple. Simply grab the code right off of their homepage or install it with Bower. Then add blanket as a library in the bottom of your qunit.html file, and then adddata-cover to all of the files you want coverage tests on.

1
2
3
4
5
    <script src="../app/yourSourceCode.js" data-cover></script>
    <script src="../js/lib/qunit/qunit/qunit.js"></script>
    <script src="../js/lib/blanket/dist/qunit/blanket.js"></script>
    <script src="tests.js"></script>
</body>

Done. Super easy, and now you’ll get an option in your QUnit runner for showing coverage:

In this example, you can see that the test coverage isn’t quite 100%, but in this case since there’s not much code, it’ll be easy to bump it up. You can actually drill down and see the exact functions that haven’t been covered yet:

Here in this case, the FormViewModel was never instantiated in the tests and therefor is missing test coverage. You can then simply add a new test that creates an instance of the FormViewModel, and perhaps write an assertion that checks that the addressproperty is present and is an instanceOf the AddressViewModel.

You’ll then get the pleasure of seeing 100% test coverage.

Advertisement

Complexity Tests

As your applications get larger and larger, it’s nice to be able to run some static analysis on your JavaScript code. A great tool for running analysis on JavaScript is called Plato.

You can run plato by installing it via npm with:

1
npm install -g plato

Then you can run plato on a directory of JavaScript code:

1
plato -r -d js/app reports

This will run Plato on all of the JavaScript located at “js/app” and output the results into reports. Plato runs all kind of metrics on your code, including average lines of code, a computed maintainability score, JSHint, difficult, estimated errors, and more.

There is not a whole lot to see in that previous image, simply because for the code we’ve been working on, there’s only one file, but when you get into working with a large application that has a lot of files and lines of code, you’ll find the information it gives you extremely useful.

It even keeps track of all of the times you’ve run it, so you can see how your statistics change over time.

Conclusion

While testing the client side seems like a difficult proposition, there are so many great tools to use these days to make it super easy. This article barely scratches the surface of all of the things out there nowadays to make client side testing easy. It can be a tedious task, but you’ll find that in the end, the benefits of having a test suite and testable code far outweighs it. Hopefully with the steps outlined here, you’ll be able to begin testing client side code quickly.