Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to test a Controller which relies on an ngResource Service
    primarykey
    data
    text
    <p>I have a controller which relies on a service built through ngResource. I am having trouble testing this(although both appear to work like a charm in the actual application). The following is the (sanitized) Controller </p> <pre><code>MyApp.Controller.MyCarsController = (scope, http, typeService) -&gt; if scope.context==undefined scope.ferrari_or_porshe ="" scope.id = "" else if scope.context=="ferrari" scope.country_or_pi ="Ferrari" else if scope.context=="porshe" scope.country_or_pi ="Porshe" typeService.index ferrari_or_porshe: scope.ferrari_or_porshe id: scope.id , (response) -&gt; scope.type = response scope.loading = false MyApp.Controller.MyCarsController.$inject = ['$scope', '$http', 'Type'] </code></pre> <p>And this is the Service:</p> <pre><code>MyApp.MyModule.factory 'Type', ['$resource', ($resource) -&gt; TypeResource = $resource("/api/types/:ferrari_or_porshe/:id", {}, index: method: "GET" isArray: true ) return TypeResource ] </code></pre> <p>Finally, some test code:</p> <pre><code>describe 'MyApp.Controller.MyCarsController', -&gt; beforeEach module('MyModule') beforeEach inject ($rootScope, $http, $controller, Type) -&gt; @scope = $rootScope.$new() @typeService = Type @scope.context = undefined $controller 'MyApp.Controller.MyCarsController', $scope: @scope describe '#home-page', -&gt; it 'contains a list of types', -&gt; expect(@scope.types.length).toBeGreaterThan 0 it "sets instance variables correctly", -&gt; expect(@scope.ferrari_or_porshe).toBe "" expect(@scope.id).toBe "" </code></pre> <p>Which fails with:</p> <pre><code> No more request expected in helpers/angular-mocks.js on line 889 TypeError: 'undefined' is not an object (evaluating 'this.scope.types.length') in controllers/my_cars_controller_spec.js </code></pre> <p>By judicious application of console.logs, I have discovered that the issue is that the final callback on response is never reached. TypeResource comes back as [Function].</p> <p>My questions is:</p> <p>How do I drive the Jasmine Tests to correctly enter the Service and fetch a response? And is there any way to create direct Unit Tests for Services?</p> <p>Any and all help is appreciated </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