16.07.2017 Views

AngularJS Essentials

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Services<br />

For now, let's create a service based on our parkingFactoryFunction function,<br />

as follows:<br />

parkingApp.js<br />

var parking = angular.module("parking", []);<br />

parkingService.js<br />

parking.factory("parkingService", function () {<br />

var _calculateTicket = function (car) {<br />

var departHour = car.depart.getHours();<br />

var entranceHour = car.entrance.getHours();<br />

var parkingPeriod = departHour - entranceHour;<br />

var parkingPrice = parkingPeriod * 10;<br />

return {<br />

period: parkingPeriod,<br />

price: parkingPrice<br />

};<br />

};<br />

return {<br />

calculateTicket: _calculateTicket<br />

};<br />

});<br />

Chapter 7<br />

To avoid duplicated setup and teardown code, Jasmine provides two important<br />

functions, beforeEach and afterEach, which are executed before and after the<br />

execution of each test. With the module function of ngMock, we can load the desired<br />

module and inject its components through the inject function just by informing<br />

the name of the component. Optionally, we may enclose the name of the component<br />

with underscores. In the following code, we are loading the parking module and<br />

injecting the parkingService specification:<br />

parkingServiceSpec.js<br />

describe("Parking Service Specification", function () {<br />

var parkingService;<br />

beforeEach(module("parking"));<br />

beforeEach(inject(function (_parkingService_) {<br />

[ 125 ]<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!