Testing

Application

Why?

tl;dr

testing is fun

types of testing in

AngularJS

Unit Testing

prerequisites for

Unit Testing

JavaScript Testing

101

Testing Framework

Major Functions

describe('Conference', function () {

});
describe('Conference', function () {

  it('should have a title', function () {
  
  });
  
});
describe('Conference', function () {

  it('should have a title', function () {
  
    expect(conference.title).toBeDefined();
    
  });
  
});

Matchers

Matchers

Negation

Spy

Matchers

var Facebook = {
  getFriends: function () {
    // FACEBOOK_FRIENDS_URL
    // 'https://www.facebook.com/friends.json'
    return $.getJSON(FACEBOOK_FRIENDS_URL);
  }
};

describe('Facebook Library', function () {

  beforeEach(function () {
    spyOn($, 'getJSON').returnValue();
  });
  
  it('should call jQuery getJSON properly', function () {
    Facebook.getFriends();
    expect($.getJSON).toHaveBeenCalledWith(FACEBOOK_FRIENDS_URL);
  });
  
});

Test Runner

Install CLI

$ npm install -g karma-cli

Initialize

It will create a karma.conf.js

$ karma init

Install

$ npm install --save-dev karma

Install Plugins

$ npm install --save-dev karma-jasmine
$ npm install --save-dev karma-chrome-launcher
$ npm install --save-dev karma-coverage

Run

$ karma start

Test

AngularJS

Module

Load Module

beforeEach( module('myApp.moduleName') );

Load Module

describe('Angular Module', function () {

  beforeEach(module('myApp.moduleName'));
  
  it('should do something awesome', function () {
    expect(true).toBeTruthy();
  }
  
});

Inject Module

beforeEach(inject(function(_$rootScope_, _MyService_) {

}));

Test Filter

describe('Some Filter', function () {
  var someFilter;
  
  beforeEach(module('myApp.filters'));
  
  beforeEach(inject(function(_$filter_) {
    someFilter = _$filter_('someFilter');
  }));
  
  it('should do something', function () {
    expect(someFilter(input)).toEqual(output);
  }
});

Test Service

describe('Some Service', function () {
  var someService;
  
  beforeEach(module('myApp.services'));
  
  beforeEach(inject(function(_someService_) {
    someService = _someService_;
  }));
  
  it('should do something', function () {
    expect(someService.foo()).toEqual(bar);
  }
});

Test Directive

describe('User Profile Directive', function () {
  var element, $scope, $compile;
  beforeEach(module('myDirectives'));
  beforeEach(inject(function(_$rootScope_, _$compile_) {
    $compile = _$compile_;
    $scope = _$rootScope_.$new();
  }));
  
  it('should do something', function () {
    element = $compile('<user-profile>')($scope);
    $scope.$digest();
    expect(element.find('something').length).toBeGreaterThan(0);
  }
});

DEMO

Thank You

fb.me/rifat