Spying on service that returns a promise - javascript

I have a service that retrieves data with a cache and a fallback to $http, and I'm trying to mock out calls to the service in a controller spec using jasmine spies. However, when I call scope.$digest, the actual service is being called and HTTP call is being made.
I have tried using all combinations of [$rootScope|scope].[$apply|$digest]() and my HTTP calls are still being made. However if I return something other than a promise from my spy, such as a string, I will get an error that then is undefined as a function, so it appears the spy is stubbing the function successfully?
Jasmine Test
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
// Should be called by each test after mocks and spies have been setup
startContoller = function() {
$controller('SearchCtrl', {
$scope: scope,
$stateParams: { q: 'test' }
});
};
}));
it('sets error message when no results', inject(function(QuestionService, $q) {
var deferred;
spyOn(QuestionService, 'search').and.callFake(function() {
deferred = $q.defer();
deferred.reject();
return deferred.promise;
});
startContoller();
scope.$digest();
expect(scope.error).toBe(true);
}));
Controller
.controller('SearchCtrl', ['$scope', '$stateParams', 'QuestionService',
function($scope, $stateParams, QuestionService) {
var query = $stateParams.q;
$scope.page = 1;
QuestionService.search(query, $scope.page).then(function(questions) {
if (questions.length === 0) {
$scope.error = true;
$scope.errorMessage = 'No Results';
} else {
$scope.questions = questions;
}
}, function() {
$scope.error = true;
});
}]);

dmahapatro's comment is the way to go.
As you are retreiving the controller using $controller('SearchCtrl'...), your service is already instanciated by the time your "it" block is executed, so spying on it has no effect.
You should be injecting the mocked service in your $controller call.
Also, no need for your startController() function, as invoking $controller will execute the controller's logic.
var QuestionServiceMock, deferred;
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
QuestionServiceMock = jasmine.createSpyObj('QuestionService', ['search']);
QuestionServiceMock.search.andCallFake(function () {
deferred = $q.defer();
deferred.reject();
return deferred.promise;
});
$controller('SearchCtrl', {
$scope: scope,
$stateParams: { q: 'test' },
QuestionService: QuestionServiceMock
});
}));
it('sets error message when no results', inject(function(QuestionService, $q) {
scope.$apply();
expect(scope.error).toBe(true);
}));

Related

Angularjs unit testing resolving promises

I'm probably doing this wrong but I can't figure out how to fix it.
I want to test a controller that uses a resource (ngResource) and I want to use a Spy as a test double for the resource so it doesn't actually do the http call. In the code below I just want to test the search function in the controller.
Controller:
controllers = angular.module('app.controllers');
controllers.controller('landingCtrl', ['$scope', '$q', 'categoryResource', function ($scope, $q, categoryResource) {
$scope.search = function (text) {
console.log('searching for: ' + text);
var deferred = $q.defer();
categoryResource.query({ searchTerm: text }, function (result) {
if (result.length == 0) {
deferred.resolve(['No results found']);
} else {
deferred.resolve(result);
}
});
return deferred.promise;
}
}]);
Service:
var services = angular.module('app.services');
services.factory('categoryResource', ['$resource', function ($resource) {
var resource = $resource('/api/category');
return resource;
}]);
Spec for landingCtrl:
describe('Controller: landingCtrl ', function () {
var $q,
$rootScope,
$scope;
beforeEach(module('ngResource'));
beforeEach(module('app.services'));
beforeEach(module('app.controllers'));
beforeEach(inject(function (_$rootScope_, _$q_) {
$q = _$q_;
$rootScope = _$rootScope_;
}));
// mock any depencencies, like scope. $resource or $http
beforeEach(inject(function ($controller, $injector, categoryResource) {
$scope = $rootScope.$new();
spyOn(categoryResource, 'query').andCallFake(function (searchText) {
console.log('query fake being called');
var deferred = $q.defer();
deferred.resolve(['Test', 'Testing', 'Protester']);
return deferred.promise;
});
landingCtrl = $controller('landingCtrl', {
'$scope': $scope,
'$q': $q,
'categoryResource': categoryResource
});
}));
afterEach(inject(function ($rootScope) {
$rootScope.$apply();
}));
it('should return words with "test" in them"', function () {
$scope.search('test').then(function (results) {
console.log(results);
expect(results).toContain('Test');
});
$scope.$apply();
});
});
The test executes without errors but it passes without ever resolving the promise so my code inside the "then" function never gets called. What am I doing wrong?
I've created a plunker with the above and a test that should fail:
http://plnkr.co/edit/adE6fTajgbDoM33rtbZS?p=preview
Your spec is mocking categoryResource.query() so it returns a promise, but your controller isn't expecting that. It calls query() and passes a callback, and within that callback it does its thing. In other words, your spec isn't testing what your controller does.
Here's your fixed spec:
spyOn(categoryResource, 'query').andCallFake(function (searchText, callback) {
console.log('query fake being called');
callback(['Test', 'Testing', 'Protester']);
});
...
it('should return words with "test" in them"', function () {
var results;
$scope.search('test').then(function (_results_) {
console.log(results);
results = _results_;
});
$scope.$apply();
expect(results).toContain('Test');
});
Working Plunker
Notice that I have moved the expectation outside the then() callback, so your test breaks if the promise isn't resolved.

How does one program PhantomJS to wait for AngularJS $resource to resolve before attempting test on returned data?

I have an AngularJS controller test script using PhantomJS. The test looks to see if the controller has loaded "users" data from a database via a RESTFul web service using AngularJS' $resource service. The problem is that the test fails because the $resource (which returns a promise I believe) isn't resolved yet when the test executes. What's the proper way to deal with this delay so that the test will pass? Here is my code:
CONTROLLER:
.controller('MainCtrl', function ($scope, Users) {
$scope.users = Users.query();
$scope.sortField = 'lastName';
$scope.reverseSort = true;
})
SERVICE:
angular.module('clearsoftDemoApp').factory('Users', function ($resource) {
return $resource('http://localhost:8080/ClearsoftDemoBackend/webresources/clearsoft.demo.users', {}, {
query: {method: 'GET', isArray: true}
});
});
TEST:
describe('Controller: MainCtrl', function () {
// load the controller's module
beforeEach(module('clearsoftDemoApp'));
var MainCtrl, scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
MainCtrl = $controller('MainCtrl', {
$scope: scope
});
}));
it('should retrieve a list of users and assign to scope.users', function () {
expect(scope.users.length).toBeGreaterThan(0);
});
});
You need to mock the factory call and pass the mock to the controller:
beforeEach(inject(function ($controller, $rootScope) {
var users = { query: function() { return [{}]; } };
scope = $rootScope.$new();
MainCtrl = $controller('MainCtrl', {
$scope: scope,
Users: users
});
}))

Test a controller with success() and error ()

I'm trying to work out the best way to unit test success and error callbacks in controllers. I am able to mock out service methods, as long as the controller only uses the default $q functions such as 'then' (see the example below). I'm having an issue when the controller responds to a 'success' or 'error' promise. (Sorry if my terminology is not correct).
Here is an example controller \ service
var myControllers = angular.module('myControllers');
myControllers.controller('SimpleController', ['$scope', 'myService',
function ($scope, myService) {
var id = 1;
$scope.loadData = function () {
myService.get(id).then(function (response) {
$scope.data = response.data;
});
};
$scope.loadData2 = function () {
myService.get(id).success(function (response) {
$scope.data = response.data;
}).error(function(response) {
$scope.error = 'ERROR';
});
};
}]);
cocoApp.service('myService', [
'$http', function($http) {
function get(id) {
return $http.get('/api/' + id);
}
}
]);
I have the following test
'use strict';
describe('SimpleControllerTests', function () {
var scope;
var controller;
var getResponse = { data: 'this is a mocked response' };
beforeEach(angular.mock.module('myApp'));
beforeEach(angular.mock.inject(function($q, $controller, $rootScope, $routeParams){
scope = $rootScope;
var myServiceMock = {
get: function() {}
};
// setup a promise for the get
var getDeferred = $q.defer();
getDeferred.resolve(getResponse);
spyOn(myServiceMock, 'get').andReturn(getDeferred.promise);
controller = $controller('SimpleController', { $scope: scope, myService: myServiceMock });
}));
it('this tests works', function() {
scope.loadData();
expect(scope.data).toEqual(getResponse.data);
});
it('this doesnt work', function () {
scope.loadData2();
expect(scope.data).toEqual(getResponse.data);
});
});
The first test passes and the second fails with the error "TypeError: Object doesn't support property or method 'success'". I get that in this instance that getDeferred.promise
does not have a success function. Okay here is the question, what is a nice way to write this test so that I can test the 'success', 'error' & 'then' conditions of a mocked service ?
I'm starting to think that I should avoid the use of success() and error() in my controllers...
EDIT
So after thinking about this some more, and thanks to the detailed answer below, I've come to the conclusion that the handling the success and error callbacks in the controller is bad. As HackedByChinese mentions below success\error is syntactic sugar that is added by $http. So, in actual fact, by trying to handle success \ error I am letting $http concerns leak into my controller, which is exactly what I was trying to avoid by wrapping the $http calls in a service. The approach I'm going to take is to change the controller not to use success \ error:
myControllers.controller('SimpleController', ['$scope', 'myService',
function ($scope, myService) {
var id = 1;
$scope.loadData = function () {
myService.get(id).then(function (response) {
$scope.data = response.data;
}, function (response) {
$scope.error = 'ERROR';
});
};
}]);
This way I can test the error \ success conditions by calling resolve() and reject() on the deferred object:
'use strict';
describe('SimpleControllerTests', function () {
var scope;
var controller;
var getResponse = { data: 'this is a mocked response' };
var getDeferred;
var myServiceMock;
//mock Application to allow us to inject our own dependencies
beforeEach(angular.mock.module('myApp'));
//mock the controller for the same reason and include $rootScope and $controller
beforeEach(angular.mock.inject(function($q, $controller, $rootScope, $routeParams) {
scope = $rootScope;
myServiceMock = {
get: function() {}
};
// setup a promise for the get
getDeferred = $q.defer();
spyOn(myServiceMock, 'get').andReturn(getDeferred.promise);
controller = $controller('SimpleController', { $scope: scope, myService: myServiceMock });
}));
it('should set some data on the scope when successful', function () {
getDeferred.resolve(getResponse);
scope.loadData();
scope.$apply();
expect(myServiceMock.get).toHaveBeenCalled();
expect(scope.data).toEqual(getResponse.data);
});
it('should do something else when unsuccessful', function () {
getDeferred.reject(getResponse);
scope.loadData();
scope.$apply();
expect(myServiceMock.get).toHaveBeenCalled();
expect(scope.error).toEqual('ERROR');
});
});
As someone had mentioned in a deleted answer, success and error are syntactic sugar added by $http so they aren't there when you create your own promise. You have two options:
1 - Don't mock the service and use $httpBackend to setup expectations and flush
The idea is to let your myService act like it normally would without knowing it's being tested. $httpBackend will let you set up expectations and responses, and flush them so you can complete your tests synchronously. $http won't be any wiser and the promise it returns will look and function like a real one. This option is good if you have simple tests with few HTTP expectations.
'use strict';
describe('SimpleControllerTests', function () {
var scope;
var expectedResponse = { name: 'this is a mocked response' };
var $httpBackend, $controller;
beforeEach(module('myApp'));
beforeEach(inject(function(_$rootScope_, _$controller_, _$httpBackend_){
// the underscores are a convention ng understands, just helps us differentiate parameters from variables
$controller = _$controller_;
$httpBackend = _$httpBackend_;
scope = _$rootScope_;
}));
// makes sure all expected requests are made by the time the test ends
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
describe('should load data successfully', function() {
beforeEach(function() {
$httpBackend.expectGET('/api/1').response(expectedResponse);
$controller('SimpleController', { $scope: scope });
// causes the http requests which will be issued by myService to be completed synchronously, and thus will process the fake response we defined above with the expectGET
$httpBackend.flush();
});
it('using loadData()', function() {
scope.loadData();
expect(scope.data).toEqual(expectedResponse);
});
it('using loadData2()', function () {
scope.loadData2();
expect(scope.data).toEqual(expectedResponse);
});
});
describe('should fail to load data', function() {
beforeEach(function() {
$httpBackend.expectGET('/api/1').response(500); // return 500 - Server Error
$controller('SimpleController', { $scope: scope });
$httpBackend.flush();
});
it('using loadData()', function() {
scope.loadData();
expect(scope.error).toEqual('ERROR');
});
it('using loadData2()', function () {
scope.loadData2();
expect(scope.error).toEqual('ERROR');
});
});
});
2 - Return a fully-mocked promise
If the thing you're testing has complicated dependencies and all the set-up is a headache, you may still want to mock the services and the calls themselves as you have attempted. The difference is that you'll want to fully mock promise. The downside of this can be creating all the possible mock promises, however you could make that easier by creating your own function for creating these objects.
The reason this works is because we pretend that it resolves by invoking the handlers provided by success, error, or then immediately, causing it to complete synchronously.
'use strict';
describe('SimpleControllerTests', function () {
var scope;
var expectedResponse = { name: 'this is a mocked response' };
var $controller, _mockMyService, _mockPromise = null;
beforeEach(module('myApp'));
beforeEach(inject(function(_$rootScope_, _$controller_){
$controller = _$controller_;
scope = _$rootScope_;
_mockMyService = {
get: function() {
return _mockPromise;
}
};
}));
describe('should load data successfully', function() {
beforeEach(function() {
_mockPromise = {
then: function(successFn) {
successFn(expectedResponse);
},
success: function(fn) {
fn(expectedResponse);
}
};
$controller('SimpleController', { $scope: scope, myService: _mockMyService });
});
it('using loadData()', function() {
scope.loadData();
expect(scope.data).toEqual(expectedResponse);
});
it('using loadData2()', function () {
scope.loadData2();
expect(scope.data).toEqual(expectedResponse);
});
});
describe('should fail to load data', function() {
beforeEach(function() {
_mockPromise = {
then: function(successFn, errorFn) {
errorFn();
},
error: function(fn) {
fn();
}
};
$controller('SimpleController', { $scope: scope, myService: _mockMyService });
});
it('using loadData()', function() {
scope.loadData();
expect(scope.error).toEqual("ERROR");
});
it('using loadData2()', function () {
scope.loadData2();
expect(scope.error).toEqual("ERROR");
});
});
});
I rarely go for option 2, even in big applications.
For what it's worth, your loadData and loadData2 http handlers have an error. They reference response.data but the handlers will be called with the parsed response data directly, not the response object (so it should be data instead of response.data).
Don't mix concerns!
Using $httpBackend inside a controller is a bad Idea since you are mixing concerns inside your Test. Whether you retrieve data from an Endpoint or not is not a concern of the Controller, is a concern of the DataService you are calling.
You can see this more clearly if you change the Endpoint Url inside the service you will then have to modify both tests: the service Test and the Controller Test.
Also as previously mentioned, the use of success and error are syntactic sugar and we should stick to the use of then and catch. But in reality you may find yourself in the need of testing "legacy" code. So for that I'm using this function:
function generatePromiseMock(resolve, reject) {
var promise;
if(resolve) {
promise = q.when({data: resolve});
} else if (reject){
promise = q.reject({data: reject});
} else {
throw new Error('You need to provide an argument');
}
promise.success = function(fn){
return q.when(fn(resolve));
};
promise.error = function(fn) {
return q.when(fn(reject));
};
return promise;
}
By calling this function you will get a true promise that respond to then and catch methods when you need to and will also work for the success or error callbacks. Note that the success and error returns a promise itself so it will work with chained then methods.
(NOTE: On the 4th and 6th line the function returns resolve and reject values inside the data property of an object. This is to mock the Behavior of $http since it returns the data, http Status etc.)
Yes, do not use $httpbackend in your controller, because we don't need to make real requests, you just need to make sure that one unit is doing it's job exactly as expected, have a look on this simple controller tests, it's easy to understand
/**
* #description Tests for adminEmployeeCtrl controller
*/
(function () {
"use strict";
describe('Controller: adminEmployeeCtrl ', function () {
/* jshint -W109 */
var $q, $scope, $controller;
var empService;
var errorResponse = 'Not found';
var employeesResponse = [
{id:1,name:'mohammed' },
{id:2,name:'ramadan' }
];
beforeEach(module(
'loadRequiredModules'
));
beforeEach(inject(function (_$q_,
_$controller_,
_$rootScope_,
_empService_) {
$q = _$q_;
$controller = _$controller_;
$scope = _$rootScope_.$new();
empService = _empService_;
}));
function successSpies(){
spyOn(empService, 'findEmployee').and.callFake(function () {
var deferred = $q.defer();
deferred.resolve(employeesResponse);
return deferred.promise;
// shortcut can be one line
// return $q.resolve(employeesResponse);
});
}
function rejectedSpies(){
spyOn(empService, 'findEmployee').and.callFake(function () {
var deferred = $q.defer();
deferred.reject(errorResponse);
return deferred.promise;
// shortcut can be one line
// return $q.reject(errorResponse);
});
}
function initController(){
$controller('adminEmployeeCtrl', {
$scope: $scope,
empService: empService
});
}
describe('Success controller initialization', function(){
beforeEach(function(){
successSpies();
initController();
});
it('should findData by calling findEmployee',function(){
$scope.findData();
// calling $apply to resolve deferred promises we made in the spies
$scope.$apply();
expect($scope.loadingEmployee).toEqual(false);
expect($scope.allEmployees).toEqual(employeesResponse);
});
});
describe('handle controller initialization errors', function(){
beforeEach(function(){
rejectedSpies();
initController();
});
it('should handle error when calling findEmployee', function(){
$scope.findData();
$scope.$apply();
// your error expectations
});
});
});
}());

AngularJs unit test - mocked promise not executing "then"

We're unit testing our controllers. We've successfully mocked the call to our REST service layer and verified that it is indeed being called with the given data. Now however we'd like to test that in our controller the execution of the then promise changes the location.path:
controller:
(function () {
app.controller('registerController', ['$scope', '$location', '$ourRestWrapper', function ($scope, $location, $ourRestWrapper) {
$scope.submitReg = function(){
// test will execute this
var promise = $ourRestWrapper.post('user/registration', $scope.register);
promise.then(function(response) {
console.log("success!"); // test never hits here
$location.path("/");
},
function(error) {
console.log("error!"); // test never hits here
$location.path("/error");
}
);
};
$ourRestWrapper.post(url,data) just wraps Restangular.all(url).post(data)..
Our Test:
(function () {
describe("controller: registerController", function() {
var scope, location, restMock, controller, q, deferred;
beforeEach(module("ourModule"));
beforeEach(function() {
restMock = {
post: function(url, model) {
console.log("deferring...");
deferred = q.defer();
return deferred.promise;
}
};
});
// init controller for test
beforeEach(inject(function($controller, $rootScope, $ourRestWrapper, $location, $q){
scope = $rootScope.$new();
location = $location;
q = $q;
controller = $controller('registerController', {
$scope: scope, $location: location, $ourRestWrapper: restMock});
}));
it('should call REST layer with registration request', function() {
scope.register = {data:'test'};
spyOn(restMock, 'post').andCallThrough();
scope.submitReg();
deferred.resolve();
// successfull
expect(restMock.post).toHaveBeenCalledWith('user/registration',scope.register);
expect(restMock.post.calls.length).toEqual(1);
// fail: Expected '' to be '/'.
expect(location.path()).toBe('/');
});
In our console we see "deferring..." and the first two expectations succeed. Why will it not call the then block (i.e. set the location)?
Cache the $rootscope object when you get it from the injector and call $rootScope.$apply() immediately after deferred.resolve().

How do I mock the result in a $http.get promise when testing my AngularJS controller?

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.
Here I have a simple factory which calls a sample API.
myApp.factory('MyFactory', ['$http',function($http) {
var people = {
requestPeople: function(x) {
var url = 'js/test.json';
return $http.get(url);
}
};
return people;
}]);
And this is how I call it in the controller
myApp.controller('MyCtrl1', ['$scope', 'MyFactory', function ($scope, MyFactory) {
MyFactory.requestPeople(22).then(function(result) {
$scope.peopleList = result;
});
}]);
While it works fine, I would like to be able to mock the result that is passed in when then is called. Is this possible?
My attempt so far has produced nothing. This is my attempt:
//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');
}));
The error that I get when running this in karma runner, is
TypeError: 'undefined' is not an object (evaluating 'scope.peopleList.one')
How can I get this test working with my mocked data?
I don't think $httpBackend is what you're after here, you want the whole factory to be mocked without it having a dependency on $http?
Take a look at $q, in particular the code sample under the Testing header. Your issue might be resolved with code that looks like this:
'use strict';
describe('mocking the factory response', function () {
beforeEach(module('myApp.controllers'));
var scope, fakeFactory, controller, q, deferred;
//Prepare the fake factory
beforeEach(function () {
fakeFactory = {
requestPeople: function () {
deferred = q.defer();
// Place the fake return object here
deferred.resolve({ "one": "three" });
return deferred.promise;
}
};
spyOn(fakeFactory, 'requestPeople').andCallThrough();
});
//Inject fake factory into controller
beforeEach(inject(function ($rootScope, $controller, $q) {
scope = $rootScope.$new();
q = $q;
controller = $controller('MyCtrl1', { $scope: scope, MyFactory: fakeFactory });
}));
it('The peopleList object is not defined yet', function () {
// Before $apply is called the promise hasn't resolved
expect(scope.peopleList).not.toBeDefined();
});
it('Applying the scope causes it to be defined', function () {
// This propagates the changes to the models
// This happens itself when you're on a web page, but not in a unit test framework
scope.$apply();
expect(scope.peopleList).toBeDefined();
});
it('Ensure that the method was invoked', function () {
scope.$apply();
expect(fakeFactory.requestPeople).toHaveBeenCalled();
});
it('Check the value returned', function () {
scope.$apply();
expect(scope.peopleList).toBe({ "one": "three" });
});
});
I've added some tests around what $apply does, I didn't know that until I started playing with this!
Gog

Categories

Resources