Note that there are some explanatory texts on larger screens.

plurals
  1. POTesting initialization logic in closure in angular service
    primarykey
    data
    text
    <p>I have an angular service that is used as a factory function to instatiate many object instances of the type Engine like this:</p> <pre><code>angular.module('parts.engine', []).factory('Engine', function() { var Engine = function( settings ) { this.hp = settings.engine.hp; this.miles = 0; }; Engine.prototype.setMiles = function( miles ) { this.miles = miles; } return Engine; }); </code></pre> <p>Say I have another angular service, that is also used to create instances of an object like this:</p> <pre><code>angular.module('car', ['parts.engine']).factory('carCreator', function( Engine ) { var carCreator = function( settings ) { var engine = new Engine( settings ); engine.setMiles( settings.engine.miles ) return { brand: settings.brand; engine: engine; } }; return carCreator; }); </code></pre> <p>So I now instatiate a new instance of a car object like this:</p> <pre><code>angular.module('carApp', ['car']).controller('AppCtrl', function( carCreator ) { var settings = { brand: 'Ford', engine: { hp: 125, miles: 12000 } }; var newCar = carCreator(settings); }); </code></pre> <p>Does anyone have an idea how to test the initialization logic:</p> <pre><code>var engine = new Engine( settings ); engine.setMiles( settings.engine.miles ) </code></pre> <p>in the carCreator factory? I know I can instantiate an object with the carCreator class and check, if the returned objects <code>engine.miles</code> property is set to the correct value. But I have cases, where checking for this will not be as easy, because the initalization logic and the values returned are much more complex. What I would like to do is test the businesslogic of <code>setMiles</code> in the Engine class, and just setup a SpyOn on <code>Engine</code> and <code>engine.setMiles</code> when testing the carCreator class, but how do I do that, when <code>engine</code> is created in the closure? </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload