SlideShare a Scribd company logo
8
Most read
13
Most read
16
Most read
Unit testing
Overview
• Unit testing frameworks
• Jasmine (in details)
• Test runners
• Karma (in details)
• Angular mocks
• Testing controllers
• Testing services
Unit testing frameworks
• Jasmine
– Exposes BDD no additional set up and
configuration required
• Mocha
– Requires additional configuration can
work as TDD or BDD. Normally is being
combined with Chai
• QUnit
Jasmine
• Requires less setup
• Is integrated with most CI
• Is supported by test runners or can run
from browser
• Is fully BDD
• Has built in assertion library
• Does not have built in mocking
frameworks(works fine with 3rd party like
Squire or angular-mocks)
• The syntax is really good
Mocha
• Requires more setup
• Is not fully integrated CI
• Although can be executed via test
runners or CI plugins
• Provides ability to choose between TDD
or BDD
• Works fine with 3rd party assertion and
mocking libraries
• Is integrated with IDE(Web Storm)
• Testing async is smooth
Jasmineshortest testsample
//describe function for the test suite
describe("This is test suite", function() {
//it function for the spec
it("contains spec with an expectation", function() {
//expect assertion function
expect(true)
//toBe is a matcher function
.toBe(true);
});
});
Jasminetest suite
• Is done with describe function
• describe expect as a first argument string
with test suite description as a second
function to be called to process test suite
• Can be nested
Test suite is a collection of test cases that are intended to be
used to test a software program to show that it has some
specified set of behaviors. A test suite often contains detailed
instructions or goals for each collection of test cases and
information on the system configuration to be used during
testing. Wiki (c)
Jasminetest spec
• Is done with it function
• it expect as a first argument string with
test suite description as a second
function to be called to process test
suite
• Contain expectations
Jasmineexpectations
• Expectations are built with the function
expect which takes a value, called the
actual. It is chained with a Matcher
function, which takes the expected value.
expect(true).toBe(true);
expect(true).not.toBe(false);
Matcherfunctions
• toBe()
• toEqual()
• toMatch()
• toBeDefined()
• toContain()
• toBeGreaterThan()
• toBeNull()
• And others
• You can create custom matchers as well
• Useful library jasmine-matchers
JasmineTearUpandTearDown
• beforeEach – tear up
• afterEach – tear down
describe("A spec (with setup and tear-down)", function() {
var foo = 0;
//will add 1 before each spec
beforeEach(function() {
foo += 1;
});
//will set it to 0 after each spec
afterEach(function() {
foo = 0;
});
//2 specs will verify that foo is equal to 1
it("is just a function, so it can contain any code", function() {
expect(foo).toEqual(1);
});
it("can have more than one expectation", function() {
expect(foo).toEqual(1);
});
});
Jasminespies
• At the very high level can be treated as
mocks
• Can mock the call and record passed
parameters
• Can return fake values
• Can mock the call and pass through to
real function
spyOn(foo, "getBar").and.returnValue(745);
spyOn(foo, 'getBar').and.callThrough();
spyOn(foo, 'setBar');
Jasminespies
describe("Spy sample", function() {
var foo, bar = null;
beforeEach(function() {
foo = {
setBar: function(value) { bar = value; }
};
//spy on set bar method
spyOn(foo, 'setBar');
foo.setBar(123);
foo.setBar(456);
});
it("tracks that the spy was called", function() {
expect(foo.setBar).toHaveBeenCalled();
});
it("tracks all the arguments of its calls", function() {
expect(foo.setBar).toHaveBeenCalledWith(123);
expect(foo.setBar).toHaveBeenCalledWith(456);
});
it("stops all execution on a function", function() {
expect(bar).toBeNull();
});
});
So how to run unit tests?
• Browser
• Test runner
– Karma
– Testem
Karma
• Runs tests in background in different
browsers
• Once code is changed on file system
reruns tests automatically
• Runs from the console
• Is integrated with IDE (WebStorm, VS)
• Requires NodeJS to be installed
Karmaconfiguration
• Install nodejs
• npm install -g karma
• npm install -g karma-cli
• Additional packs:
– karma-jasmine
– karma-junit-reporter
– karma-ng-scenario – e2e testing
– karma-ng-html2js-preprocessor – load all
templates and do not load them from server
– karma-phantomjs-launcher
Karmaconfiguration
Sample: http://jsfiddle.net/gdn0jocf/
• Doc: http://karma-
runner.github.io/0.8/config/configuratio
n-file.html
How to run it?
• Command line: karma start
configfilename
• Grunt task grunt task
DEMO
Unit testcontrollersample
describe('Home controller test', function () {
//loading module where controller is defined
beforeEach(module('app.home'));
//declaring variables that will be used in the tests
var controller, scope, deferred;
//creating items
beforeEach(inject(function ($rootScope, $controller, $q) {
deferred = $q.defer();
scope = $rootScope.$new();
//create the controller injecting the scope and the mocked service
controller = $controller('Home', {
$scope: scope,
DashboardService: {
getDashboard: function () {
return deferred.promise;
}
}
});
}));
//once result is not returned let's check that initial data state is correct
it('verifies NewMessagesCount is undefined', function () {
expect(controller.NewMessagesCount === undefined);
});
//Let's resolve value and see if it is correct
it('verifies NewMessagesCount is correct', function () {
deferred.resolve({ NewMessagesCount: 5 });
expect(controller.NewMessagesCount === 5);
});
it('verifies that scope contains go and it is a function', function () {
expect(scope.go === 'function');
});
});
Unit testservicesample
describe('Dashboard factory tests', function () {
//injecting module
beforeEach(module('app.services'));
//mocking dependcies
beforeEach(function () {
var Utility = {};
module(function ($provide) {
$provide.value('Utility', Utility);
});
});
var httpBackend, Factory;
//injecting httpBackend for testing of http
//injecting factory itself
beforeEach(inject(function ($httpBackend, Factory) {
httpBackend = $httpBackend;
Factory = Factory;
}));
it('checks that object is not modified by service and proper API method is called',
function () {
//setting method we expect to be called and method response
httpBackend.expectGET('api/Dashboard/').respond("Test");
var result = Factory.getDashboard();
//Verifying that all expected methods were called
httpBackend.flush();
//verifying that result is returned as expected
expect(result == "Test");
});
afterEach(function () {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
});
Unit teste2e sample
describe(
‘Angular App',
function () {
describe(‘Angular libraries list',
function () {
beforeEach(function () {
browser().navigateTo('/app/index.html');
});
it(
'should filter the list as user types into the search box',
function () {
expect(repeater('.users li').count()).toBe(5);
input('query').enter(‘angular-ui');
expect(repeater('.users li').count()).toBe(1);
input('query').enter('');
expect(repeater('.users li').count()).toBe(5);
}
);
} );});
Unit testing in JavaScript with Jasmine and Karma

More Related Content

What's hot (20)

PPTX
Unit testing JavaScript: Jasmine & karma intro
Maurice De Beijer [MVP]
 
PDF
Unit Testing in Angular
Knoldus Inc.
 
PPTX
Testing microservices with rest assured
Kushan Shalindra Amarasiri - Technical QE Specialist
 
PPTX
Angular Unit Testing
Alessandro Giorgetti
 
PPTX
Api Testing
Vishwanath KC
 
PPTX
Api testing
Keshav Kashyap
 
PDF
Unit Testing with Jest
Maayan Glikser
 
PPTX
Jasmine framework
Vishwanath KC
 
PDF
Angularjs - Unit testing introduction
Nir Kaufman
 
PPTX
Performance testing using jmeter
Rachappa Bandi
 
PPSX
Junit
FAROOK Samath
 
PPTX
Test NG Framework Complete Walk Through
Narendran Solai Sridharan
 
PPT
testng
harithakannan
 
PDF
Introduction to jest
pksjce
 
PPS
JUnit Presentation
priya_trivedi
 
PPTX
Mobile Automation with Appium
Manoj Kumar Kumar
 
PDF
API Testing
Bikash Sharma
 
PPSX
Kotlin Language powerpoint show file
Saurabh Tripathi
 
PDF
Network Protocol Testing Using Robot Framework
Payal Jain
 
PPT
Java basic
Arati Gadgil
 
Unit testing JavaScript: Jasmine & karma intro
Maurice De Beijer [MVP]
 
Unit Testing in Angular
Knoldus Inc.
 
Testing microservices with rest assured
Kushan Shalindra Amarasiri - Technical QE Specialist
 
Angular Unit Testing
Alessandro Giorgetti
 
Api Testing
Vishwanath KC
 
Api testing
Keshav Kashyap
 
Unit Testing with Jest
Maayan Glikser
 
Jasmine framework
Vishwanath KC
 
Angularjs - Unit testing introduction
Nir Kaufman
 
Performance testing using jmeter
Rachappa Bandi
 
Test NG Framework Complete Walk Through
Narendran Solai Sridharan
 
Introduction to jest
pksjce
 
JUnit Presentation
priya_trivedi
 
Mobile Automation with Appium
Manoj Kumar Kumar
 
API Testing
Bikash Sharma
 
Kotlin Language powerpoint show file
Saurabh Tripathi
 
Network Protocol Testing Using Robot Framework
Payal Jain
 
Java basic
Arati Gadgil
 

Viewers also liked (20)

PDF
JavaScript TDD with Jasmine and Karma
Christopher Bartling
 
PDF
Karma - JS Test Runner
Sebastiano Armeli
 
PDF
AngularJS Unit Testing w/Karma and Jasmine
foxp2code
 
PPTX
TDD Basics with Angular.js and Jasmine
Luis Sánchez Castellanos
 
PDF
Angular 2 - What's new and what's different
Priscila Negreiros
 
PDF
Intro to testing Javascript with jasmine
Timothy Oxley
 
PDF
Jasmine BDD for Javascript
Luis Alfredo Porras Páez
 
PDF
Test-Driven Development of AngularJS Applications
FITC
 
PPT
Jasmine - A BDD test framework for JavaScript
Sumanth krishna
 
ODP
Unit Testing and Coverage for AngularJS
Knoldus Inc.
 
PDF
Advanced Jasmine - Front-End JavaScript Unit Testing
Lars Thorup
 
PPTX
SDN: The productive developer guide to Angular 2
Maurice De Beijer [MVP]
 
PPTX
Typescript kata The TDD style 2 edition
Ronnie Hegelund
 
PDF
Reliable Javascript
Glenn Stovall
 
KEY
Testing Client-side Code with Jasmine and CoffeeScript
Brian Hogan
 
PDF
DEV.BG - Angular 1 and Jasmine (Unit Testing and TDD)
Dimitar Danailov
 
PPTX
Behavior Driven Development with AngularJS & Jasmine
Remus Langu
 
PPT
JavaScript Testing: Mocha + Chai
James Cryer
 
PDF
UI Testing Automation
AgileEngine
 
PPTX
Coded ui test
Abhimanyu Singhal
 
JavaScript TDD with Jasmine and Karma
Christopher Bartling
 
Karma - JS Test Runner
Sebastiano Armeli
 
AngularJS Unit Testing w/Karma and Jasmine
foxp2code
 
TDD Basics with Angular.js and Jasmine
Luis Sánchez Castellanos
 
Angular 2 - What's new and what's different
Priscila Negreiros
 
Intro to testing Javascript with jasmine
Timothy Oxley
 
Jasmine BDD for Javascript
Luis Alfredo Porras Páez
 
Test-Driven Development of AngularJS Applications
FITC
 
Jasmine - A BDD test framework for JavaScript
Sumanth krishna
 
Unit Testing and Coverage for AngularJS
Knoldus Inc.
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Lars Thorup
 
SDN: The productive developer guide to Angular 2
Maurice De Beijer [MVP]
 
Typescript kata The TDD style 2 edition
Ronnie Hegelund
 
Reliable Javascript
Glenn Stovall
 
Testing Client-side Code with Jasmine and CoffeeScript
Brian Hogan
 
DEV.BG - Angular 1 and Jasmine (Unit Testing and TDD)
Dimitar Danailov
 
Behavior Driven Development with AngularJS & Jasmine
Remus Langu
 
JavaScript Testing: Mocha + Chai
James Cryer
 
UI Testing Automation
AgileEngine
 
Coded ui test
Abhimanyu Singhal
 
Ad

Similar to Unit testing in JavaScript with Jasmine and Karma (20)

PDF
Angular testing
Raissa Ferreira
 
PPTX
Angular Unit Testing
Avi Engelshtein
 
PDF
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
Christopher Bartling
 
PPTX
jasmine
Asanka Indrajith
 
PDF
Quick Tour to Front-End Unit Testing Using Jasmine
Gil Fink
 
PDF
Front end unit testing using jasmine
Gil Fink
 
PDF
AngularJS Unit Test
Chiew Carol
 
PDF
Quick tour to front end unit testing using jasmine
Gil Fink
 
PDF
JavaCro'14 - Unit testing in AngularJS – Slaven Tomac
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
PPTX
Unit testing of java script and angularjs application using Karma Jasmine Fra...
Samyak Bhalerao
 
PPTX
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
Ortus Solutions, Corp
 
PDF
3 WAYS TO TEST YOUR COLDFUSION API
Gavin Pickin
 
PDF
3 WAYS TO TEST YOUR COLDFUSION API -
Ortus Solutions, Corp
 
PPTX
Slaven tomac unit testing in angular js
Slaven Tomac
 
PDF
JavaScript Unit Testing with an Angular 5.x Use Case 101
Hazem Saleh
 
PDF
Angular Testing
Kourosh Sajjadi
 
PDF
Quick tour to front end unit testing using jasmine
Gil Fink
 
PDF
Javascript TDD with Jasmine, Karma, and Gulp
All Things Open
 
PDF
Intro to Unit Testing in AngularJS
Jim Lynch
 
PDF
Jasmine - why JS tests don't smell fishy
Igor Napierala
 
Angular testing
Raissa Ferreira
 
Angular Unit Testing
Avi Engelshtein
 
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
Christopher Bartling
 
Quick Tour to Front-End Unit Testing Using Jasmine
Gil Fink
 
Front end unit testing using jasmine
Gil Fink
 
AngularJS Unit Test
Chiew Carol
 
Quick tour to front end unit testing using jasmine
Gil Fink
 
JavaCro'14 - Unit testing in AngularJS – Slaven Tomac
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
Unit testing of java script and angularjs application using Karma Jasmine Fra...
Samyak Bhalerao
 
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
Ortus Solutions, Corp
 
3 WAYS TO TEST YOUR COLDFUSION API
Gavin Pickin
 
3 WAYS TO TEST YOUR COLDFUSION API -
Ortus Solutions, Corp
 
Slaven tomac unit testing in angular js
Slaven Tomac
 
JavaScript Unit Testing with an Angular 5.x Use Case 101
Hazem Saleh
 
Angular Testing
Kourosh Sajjadi
 
Quick tour to front end unit testing using jasmine
Gil Fink
 
Javascript TDD with Jasmine, Karma, and Gulp
All Things Open
 
Intro to Unit Testing in AngularJS
Jim Lynch
 
Jasmine - why JS tests don't smell fishy
Igor Napierala
 
Ad

Recently uploaded (20)

PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
Digital Circuits, important subject in CS
contactparinay1
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 

Unit testing in JavaScript with Jasmine and Karma

  • 2. Overview • Unit testing frameworks • Jasmine (in details) • Test runners • Karma (in details) • Angular mocks • Testing controllers • Testing services
  • 3. Unit testing frameworks • Jasmine – Exposes BDD no additional set up and configuration required • Mocha – Requires additional configuration can work as TDD or BDD. Normally is being combined with Chai • QUnit
  • 4. Jasmine • Requires less setup • Is integrated with most CI • Is supported by test runners or can run from browser • Is fully BDD • Has built in assertion library • Does not have built in mocking frameworks(works fine with 3rd party like Squire or angular-mocks) • The syntax is really good
  • 5. Mocha • Requires more setup • Is not fully integrated CI • Although can be executed via test runners or CI plugins • Provides ability to choose between TDD or BDD • Works fine with 3rd party assertion and mocking libraries • Is integrated with IDE(Web Storm) • Testing async is smooth
  • 6. Jasmineshortest testsample //describe function for the test suite describe("This is test suite", function() { //it function for the spec it("contains spec with an expectation", function() { //expect assertion function expect(true) //toBe is a matcher function .toBe(true); }); });
  • 7. Jasminetest suite • Is done with describe function • describe expect as a first argument string with test suite description as a second function to be called to process test suite • Can be nested Test suite is a collection of test cases that are intended to be used to test a software program to show that it has some specified set of behaviors. A test suite often contains detailed instructions or goals for each collection of test cases and information on the system configuration to be used during testing. Wiki (c)
  • 8. Jasminetest spec • Is done with it function • it expect as a first argument string with test suite description as a second function to be called to process test suite • Contain expectations
  • 9. Jasmineexpectations • Expectations are built with the function expect which takes a value, called the actual. It is chained with a Matcher function, which takes the expected value. expect(true).toBe(true); expect(true).not.toBe(false);
  • 10. Matcherfunctions • toBe() • toEqual() • toMatch() • toBeDefined() • toContain() • toBeGreaterThan() • toBeNull() • And others • You can create custom matchers as well • Useful library jasmine-matchers
  • 11. JasmineTearUpandTearDown • beforeEach – tear up • afterEach – tear down describe("A spec (with setup and tear-down)", function() { var foo = 0; //will add 1 before each spec beforeEach(function() { foo += 1; }); //will set it to 0 after each spec afterEach(function() { foo = 0; }); //2 specs will verify that foo is equal to 1 it("is just a function, so it can contain any code", function() { expect(foo).toEqual(1); }); it("can have more than one expectation", function() { expect(foo).toEqual(1); }); });
  • 12. Jasminespies • At the very high level can be treated as mocks • Can mock the call and record passed parameters • Can return fake values • Can mock the call and pass through to real function spyOn(foo, "getBar").and.returnValue(745); spyOn(foo, 'getBar').and.callThrough(); spyOn(foo, 'setBar');
  • 13. Jasminespies describe("Spy sample", function() { var foo, bar = null; beforeEach(function() { foo = { setBar: function(value) { bar = value; } }; //spy on set bar method spyOn(foo, 'setBar'); foo.setBar(123); foo.setBar(456); }); it("tracks that the spy was called", function() { expect(foo.setBar).toHaveBeenCalled(); }); it("tracks all the arguments of its calls", function() { expect(foo.setBar).toHaveBeenCalledWith(123); expect(foo.setBar).toHaveBeenCalledWith(456); }); it("stops all execution on a function", function() { expect(bar).toBeNull(); }); });
  • 14. So how to run unit tests? • Browser • Test runner – Karma – Testem
  • 15. Karma • Runs tests in background in different browsers • Once code is changed on file system reruns tests automatically • Runs from the console • Is integrated with IDE (WebStorm, VS) • Requires NodeJS to be installed
  • 16. Karmaconfiguration • Install nodejs • npm install -g karma • npm install -g karma-cli • Additional packs: – karma-jasmine – karma-junit-reporter – karma-ng-scenario – e2e testing – karma-ng-html2js-preprocessor – load all templates and do not load them from server – karma-phantomjs-launcher
  • 17. Karmaconfiguration Sample: http://jsfiddle.net/gdn0jocf/ • Doc: http://karma- runner.github.io/0.8/config/configuratio n-file.html
  • 18. How to run it? • Command line: karma start configfilename • Grunt task grunt task DEMO
  • 19. Unit testcontrollersample describe('Home controller test', function () { //loading module where controller is defined beforeEach(module('app.home')); //declaring variables that will be used in the tests var controller, scope, deferred; //creating items beforeEach(inject(function ($rootScope, $controller, $q) { deferred = $q.defer(); scope = $rootScope.$new(); //create the controller injecting the scope and the mocked service controller = $controller('Home', { $scope: scope, DashboardService: { getDashboard: function () { return deferred.promise; } } }); })); //once result is not returned let's check that initial data state is correct it('verifies NewMessagesCount is undefined', function () { expect(controller.NewMessagesCount === undefined); }); //Let's resolve value and see if it is correct it('verifies NewMessagesCount is correct', function () { deferred.resolve({ NewMessagesCount: 5 }); expect(controller.NewMessagesCount === 5); }); it('verifies that scope contains go and it is a function', function () { expect(scope.go === 'function'); }); });
  • 20. Unit testservicesample describe('Dashboard factory tests', function () { //injecting module beforeEach(module('app.services')); //mocking dependcies beforeEach(function () { var Utility = {}; module(function ($provide) { $provide.value('Utility', Utility); }); }); var httpBackend, Factory; //injecting httpBackend for testing of http //injecting factory itself beforeEach(inject(function ($httpBackend, Factory) { httpBackend = $httpBackend; Factory = Factory; })); it('checks that object is not modified by service and proper API method is called', function () { //setting method we expect to be called and method response httpBackend.expectGET('api/Dashboard/').respond("Test"); var result = Factory.getDashboard(); //Verifying that all expected methods were called httpBackend.flush(); //verifying that result is returned as expected expect(result == "Test"); }); afterEach(function () { httpBackend.verifyNoOutstandingExpectation(); httpBackend.verifyNoOutstandingRequest(); }); });
  • 21. Unit teste2e sample describe( ‘Angular App', function () { describe(‘Angular libraries list', function () { beforeEach(function () { browser().navigateTo('/app/index.html'); }); it( 'should filter the list as user types into the search box', function () { expect(repeater('.users li').count()).toBe(5); input('query').enter(‘angular-ui'); expect(repeater('.users li').count()).toBe(1); input('query').enter(''); expect(repeater('.users li').count()).toBe(5); } ); } );});