Testing
Application
types of testing in
AngularJS
prerequisites for
Unit Testing
- Testing Framework
- Test Runner
Major Functions
describe
it
expect
beforeEach
afterEach
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
.toBe(7)
.toEqual(obj)
.toTruthy()
.toFalsy()
.toBeDefined()
.toBeUndefined()
Matchers
.toMatch(/[a-z]+/)
.toContain('Hello')
.toBeLessThan(10)
.toBeGreaterThan(5)
.toBeNull()
.toThrow()
Negation
.not.toBe(7)
.not.toBeNull()
.not.toThrow()
Spy
.and.callThrough()
.and.returnValue(100)
.and.callFake(callback)
.and.throwError(error)
.and.stub()
Matchers
.toHaveBeenCalled()
.toHaveBeenCalledWith(params)
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);
});
});
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
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);
}
});
Thank You