O'Reilly logo

AngularJS: Up and Running by Brad Green, Shyam Seshadri

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 9. Unit Testing Filters

In Chapter 8, we covered how we could use existing AngularJS filters, as well as create our own filters. Filters are a great way of separating out common formatting and conversion logic into separate reusable components. In previous chapters, we saw how easy it was to create our own controllers and services, as well as unit test them.

In this chapter, we will work with the timeAgo filter we created in the previous chapter. We will first add complexity by adding optional parameters to the filter. Then we will unit test it step by step. By the end of the chapter, we will have Jasmine unit tests for all possible cases of our timeAgo filter.

The Filter Under Test

Let’s use the timeAgo filter from Creating AngularJS Filters as a base, and then add an optional argument to decide whether it should show the “seconds ago” message, or if it should start from the “minutes ago” message level only:

// File: chapter9/timeAgoFilter.js
angular.module('filtersApp', [])
  .filter('timeAgo', [function() {
    var ONE_MINUTE = 1000 * 60;
    var ONE_HOUR = ONE_MINUTE * 60;
    var ONE_DAY = ONE_HOUR * 24;
    var ONE_MONTH = ONE_DAY * 30;

    return function(ts, optShowSecondsMessage) {
      if (optShowSecondsMessage !== false) {
        optShowSecondsMessage = true;
      }

      var currentTime = new Date().getTime();
      var diff = currentTime - ts;
      if (diff < ONE_MINUTE && optShowSecondsMessage) {
        return 'seconds ago';
      } else if (diff < ONE_HOUR) {
        return 'minutes ago';
      } else if (diff < ONE_DAY) {
        return 'hours ago' ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required