Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I mock the result in a $http.get promise when testing my AngularJS controller?
    primarykey
    data
    text
    <p>After much reading, it seems that the recommended way to call a web service from an AngularJS controller is to use a factory and return a promise from that. </p> <p>Here I have a simple factory which calls a sample API.</p> <pre><code>myApp.factory('MyFactory', ['$http',function($http) { var people = { requestPeople: function(x) { var url = 'js/test.json'; return $http.get(url); } }; return people; }]); </code></pre> <p>And this is how I call it in the controller</p> <pre><code>myApp.controller('MyCtrl1', ['$scope', 'MyFactory', function ($scope, MyFactory) { MyFactory.requestPeople(22).then(function(result) { $scope.peopleList = result; }); }]); </code></pre> <p>While it works fine, I would like to be able to mock the <code>result</code> that is passed in when <code>then</code> is called. Is this possible? </p> <p>My attempt so far has produced nothing. This is my attempt:</p> <pre><code>//Fake service var mockService = { requestPeople: function () { return { then: function () { return {"one":"three"}; } } } }; //Some setup beforeEach(module('myApp.controllers')); var ctrl, scope; beforeEach(inject(function ($rootScope, $controller) { scope = $rootScope.$new(); ctrl = $controller('MyCtrl1', { $scope: scope, MyFactory: mockService }); })); //Test it('Event Types Empty should default to false', inject(function () { expect(scope.peopleList.one).toBe('three'); })); </code></pre> <p>The error that I get when running this in karma runner, is</p> <p>TypeError: 'undefined' is not an object (evaluating 'scope.peopleList.one')</p> <p>How can I get this test working with my mocked data?</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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