Testing AngularJS with Jasmine / Karma with $httpBackend not working - javascript

I'm trying to unit test my app built on Angular with Jasmine via Karma. The app involves making a call to the GitHub API and pulling the names of all the repos of a user and filling an array with those names. I'm trying to test that the array is getting filled but I'm having some issues with $httpBackend.
The relevant parts of my controller are:
readmeSearch.controller('ReadMeSearchController', ['RepoSearch', function(RepoSearch) {
var self = this;
self.gitRepoNames = [];
self.doSearch = function() {
var namesPromise =
RepoSearch.query(self.username)
.then(function(repoResponse) {
addRepoNames(repoResponse);
}).catch(function(error) {
console.log('error: ' + error);
});
return namesPromise;
};
addRepoNames = function(response) {
self.repoSearchResult = response.data;
for(var i = 0; i < self.repoSearchResult.length; i++) {
var name = self.repoSearchResult[i]['name']
self.gitRepoNames.push(name);
};
};
}]);
My RepoSearch factory is:
readmeSearch.factory('RepoSearch', ['$http', function($http) {
return {
query: function(searchTerm) {
return $http({
url: 'https://api.github.com/users/' + searchTerm + '/repos',
method: 'GET',
params: {
'access_token': gitAccessToken
}
});
}
};
}]);
And the test in question is this:
describe('ReadMeSearchController', function() {
beforeEach(module('ReadMeter'));
var ctrl;
beforeEach(inject(function($controller) {
ctrl = $controller('ReadMeSearchController');
}));
describe('when searching for a user\'s repos', function() {
var httpBackend;
beforeEach(inject(function($httpBackend) {
httpBackend = $httpBackend
httpBackend
.expectGET('https://api.github.com/users/hello/repos?access_token=' + gitAccessToken)
.respond(
{ data: items }
);
}));
afterEach(function() {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
var items = [
{
"name": "test1"
},
{
"name": "test2"
}
];
it('adds search results to array of repo names', function() {
ctrl.username = 'hello';
ctrl.doSearch();
httpBackend.flush();
expect(ctrl.gitRepoNames).toEqual(["test1", "test2"]);
});
});
});
When I run the test I get the error
Expected [ ] to equal [ 'test1', 'test2' ].
So evidently this is because self.gitRepoNames is not being filled. When I console log ctrl.repoSearchResult just before the expectation in the test I get
Object{data: [Object{name: ...}, Object{name: ...}]}
Which is where the problem is I feel since self.repoSearchResult.length will be undefined when it is called in the for loop in the addRepoNames function.
So my question is why doesn't response.data return an array when it is called in the addRepoNames function in the test?
Any help would be greatly appreciated.
EDIT: I should mention that the app works fine when run on the server.

ctrl.doSearch is an asynchronous function. You should handle it in an async way. Try:
it('adds search results to array of repo names', function(done) {
ctrl.username = 'hello';
ctrl.doSearch().then(function() {
expect(ctrl.gitRepoNames).toEqual(["test1", "test2"]);
done();
});
httpBackend.flush();
});

Related

AngularJS $scope variable change in .then() unit testing

I'm trying to unit test a function within my controller but am unable to get a $scope variable to be testable. I'm setting the variable in my controller's .then() and want to unit test to make sure this is set appropriately when it hits the .then block.
My test controller code:
function submit() {
myService.submit().then(function(responseData){
if(!responseData.errors) {
$scope.complete = true;
$scope.details = [
{
value: $scope.formattedCurrentDate
},
{
value: "$" + $scope.premium.toFixed(2)
},
];
} else {
$scope.submitError = true;
}
});
}
Where this service call goes is irrelevant. It will return JSON with action: 'submitted', 'response' : 'some response'. The .then() checks if errors are present on responseData, and if not it should set some details. These $scope.details are what I'm trying to test in my unit test below:
it('should handle submit details', function () {
var result;
var premium = 123.45;
var formattedCurrentDate = "2016-01-04";
var promise = myService.submit();
mockResponse = {
action: 'submitted',
response: 'some response'
};
var mockDetails = [
{
value: formattedCurrentDate
},
{
value: "$"+ premium.toFixed(2)
}
];
//Resolve the promise and store results
promise.then(function(res) {
result = res;
});
//Apply scope changes
$scope.$apply();
expect(mockDetails).toEqual(submitController.details);
});
I'm receiving an error that $scope.details is undefined. I'm not sure how to make the test recognize this $scope data changing within the controller.
Before each and other functions in my unit test:
function mockPromise() {
return {
then: function(callback) {
if (callback) {
callback(mockResponse);
}
}
}
}
beforeEach(function() {
mockResponse = {};
module('myApp');
module(function($provide) {
$provide.service('myService', function() {
this.submit = jasmine.createSpy('submit').and.callFake(mockPromise);
});
});
inject(function($injector) {
$q = $injector.get('$q');
$controller = $injector.get('$controller');
$scope = $injector.get('$rootScope');
myService = $injector.get('myService');
submitController = $controller('myController', { $scope: $scope, $q : $q, myService: myService});
});
});
How do I resolve the promise within my unit test so that I can $scope.$digest() and see the $scope variable change?
You should look how to test promises with jasmine
http://ng-learn.org/2014/08/Testing_Promises_with_Jasmine_Provide_Spy/
using a callFake would do what you try to mock
spyOn(myService, 'submit').and.callFake(function() {
return {
then: function(callback) { return callback(yourMock); }
};
});

Jasmine test using spyon with $httpBackend not working

I am trying to write a jasmine test on some javascript using spyon over a method that uses $http. I have mocked this out using $httpBackend and unfortunately the spy doesn't seem to be picking up the fact the method has indeed been called post $http useage. I can see it being called in debug, so unsure why it reports it hasn't been called. I suspect I have a problem with my scope usage ? or order of $httpBackend.flush\verify ?:
Code under test
function FileUploadController($scope, $http, SharedData, uploadViewModel) {
Removed variables for brevity
.....
$scope.pageLoad = function () {
$scope.getPeriods();
if ($scope.uploadViewModel != null && $scope.uploadViewModel.UploadId > 0) {
$scope.rulesApplied = true;
$scope.UploadId = $scope.uploadViewModel.UploadId;
$scope.linkUploadedData();
} else {
$scope.initDataLinkages();
}
}
$scope.initDataLinkages = function () {
$http({ method: "GET", url: "/api/uploadhistory" }).
success(function (data, status) {
$scope.status = status;
$scope.setUploadHistory(data);
}).
error(function (data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
}
$scope.setUploadHistory = function (data) {
if ($scope.UploadId > 0) {
$scope.currentUpload = data.filter(function (item) {
return item.UploadId === $scope.UploadId;
})[0];
//Remove the current upload, to prevent scaling the same data!
var filteredData = data.filter(function (item) {
return item.UploadId !== $scope.UploadId;
});
var defaultOption = {
UploadId: -1,
Filename: 'this file',
TableName: null,
DateUploaded: null
};
$scope.UploadHistory = filteredData;
$scope.UploadHistory.splice(0, 0, defaultOption);
$scope.UploadHistoryId = -1;
$scope.UploadTotal = $scope.currentUpload.TotalAmount;
} else {
$scope.UploadHistory = data;
}
}
Test setup
beforeEach(module('TDAnalytics'));
beforeEach(inject(function (_$rootScope_, $controller, _$httpBackend_) {
$rootScope = _$rootScope_;
$scope = $rootScope.$new();
$httpBackend = _$httpBackend_;
var sharedData = { currentBucket: { ID: 1 } };
controller = $controller('FileUploadController', { $scope: $scope, SharedData: sharedData, uploadViewModel: null });
$httpBackend.when('GET', '/api/Periods').respond(periods);
$httpBackend.when('GET', '/api/uploadhistory').respond(uploadHistory);
$scope.mappingData = {
FieldMappings: [testDescriptionRawDataField, testSupplierRawDataField],
UserFields: [testDescriptionUserField, testSupplierUserField]
};
}));
afterEach(function() {
testDescriptionRawDataField.UserFields = [];
testSupplierRawDataField.UserFields = [];
testTotalRawDataField.UserFields = [];
$httpBackend.flush();
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
Working test:
it('pageLoad should call linkUploadedData when user has navigated to the page via the Data Upload History and uploadViewModel.UploadId is set', function () {
// Arrange
spyOn($scope, 'linkUploadedData');
$scope.uploadViewModel = {UploadId: 1};
// Act
$scope.pageLoad();
// Assert
expect($scope.rulesApplied).toEqual(true);
expect($scope.linkUploadedData.calls.count()).toEqual(1);
});
Test that doesn't work (but should. returns count-0 but is called)
it('pageLoad should call setUploadHistory when data returned successfully', function () {
// Arrange
spyOn($scope, 'setUploadHistory');
// Act
$scope.initDataLinkages();
// Assert
expect($scope.setUploadHistory.calls.count()).toEqual(1);
});
The issue is you call httpBackend.flush() after the expect, which means success is called after you do your tests. You must flush before the expect statement.
it('pageLoad should call setUploadHistory when data returned successfully',
inject(function ($httpBackend, $rootScope) {
// Arrange
spyOn($scope, 'setUploadHistory');
// Act
$scope.initDataLinkages();
$httpBackend.flush();
$rootScope.$digest()
// Assert
expect($scope.setUploadHistory.calls.count()).toEqual(1);
}));
You may need to remove the flush statement from after your tests, but it probably should not be there anyway because usually it's a core part of testing behaviour and should be before expect statements.

Unit testing an AngularJS service with angular-translate calls

I've tried numerous different ways of writing a unit test for an AngularJS service that calls angular-translate, and I just can't get it to work out. Any advice would be appreciated. Here's my most promising example:
(function() {
var app = angular.module("theApp", ["pascalprecht.translate"]);
var theService = function($translate) {
var theFunction = function(data) {
return $translate("FOO", { input: data.in }).then(function(trans) {
data.out = trans;
});
};
return {
theFunction: theFunction
};
};
app.factory("theService", ["$translate", theService]);
}());
describe("theService", function() {
beforeEach(module("theApp", function($translateProvider, $provide) {
$translateProvider.useLoader('customLoader');
$provide.service('customLoader', function($q) {
return function() {
var deferred = $q.defer();
deferred.resolve({
"FOO": "foo {{input}}"
});
return deferred.promise;
};
});
}));
it("function translates input", inject(function($rootScope, theService) {
var data = { in: "bar", out: "fail" };
theService.theFunction(data);
$rootScope.$apply();
expect(data.out).toBe("foo bar");
}));
});
A JSFiddle can be found here: http://jsfiddle.net/danBhentschel/q71r874t/
Okay. I guess I figured it out on my own. I started out with the test found here:
https://github.com/angular-translate/angular-translate/blob/master/test/unit/service/translate.spec.js#L409
And I was able to slowly morph this passing test into what I wanted to do:
(function() {
var app = angular.module("theApp", ["pascalprecht.translate"]);
var theService = function($translate) {
var theFunction = function(data) {
return $translate("FOO", { input: data.in }).then(function(trans) {
data.out = trans;
});
};
return {
theFunction: theFunction
};
};
app.factory("theService", ["$translate", theService]);
}());
describe("theService", function() {
var $rootScope;
beforeEach(module("theApp", function($translateProvider, $provide) {
$translateProvider.useLoader("customLoader");
$provide.service("customLoader", function($q) {
return function() {
var deferred = $q.defer();
deferred.resolve({
"FOO": "foo {{input}}"
});
return deferred.promise;
};
});
}));
beforeEach(inject(function ($translate, _$rootScope_) {
$rootScope = _$rootScope_;
$translate.use("en_US");
$rootScope.$apply();
}));
it("function translates input", inject(function(theService) {
var data = { in: "bar", out: "fail" };
theService.theFunction(data);
$rootScope.$apply();
expect(data.out).toBe("foo bar");
}));
});
A JSFiddle with the solution can be found here: http://jsfiddle.net/danBhentschel/yLt3so14/
Please feel free to point out any stupid mistakes I made. I'm still kinda new at this.

FakeServer not returning fake data when running test with Jasmine and Sinon

I'm trying to test that some observables arrays in a ko viewmodel are set after an ajax request. I'm using Jasmine and Sinon. My issue is that my land observablearray is empty when doing an expected test. What have I missed when it comes to set up the sinon fakeserver and returns?
Btw, this works just fine when running live.
My ko model and viewmodel:
var MB = MB || {};
$(function() {
MB.KontaktModel = function(model) {
"use strict";
var self = this;
self.id = ko.observable(model.Id);
self.land = ko.observableArray([]);
self.kategori = ko.observableArray([]);
};
MB.KontaktViewModel = function() {
"use strict";
var numberCrusher = new MB.NumberCrusher(),
kontakt = ko.observable(),
land = ko.observableArray([]),
kategori = ko.observableArray([]),
loadKontakt = function(model) {
var newModel = new MB.KontaktModel(model);
.......some other setting happens here
MB.CrmService.GetLand(function (data) {
ko.mapping.fromJS($.parseJSON(data), {}, land);
kontakt().land(land());
MB.UiFixUp.RefreshChosenAfterDataUpdate();
if (!idIsEmpty) {
MB.ChosenAction.SeDefaultValue("chosen-landId", model.LandId);
}
});
MB.CrmService.GetKategori(function (data) {
ko.mapping.fromJS($.parseJSON(data), {}, kategori);
newModel.kategori(kategori);
kontakt().kategori(kategori());
MB.UiFixUp.RefreshChosenAfterDataUpdate();
if (!idIsEmpty) {
MB.ChosenAction.SeDefaultValue("chosen-kontaktKategori", model.KategoriId);
}
});
kontakt(newModel);
};
return {
kontakt: kontakt,
loadKontakt: loadKontakt
};
}();
});
CrmService:
MB.CrmService = function() {
"use strict";
var serviceBaseCrm = '/crm/kontakt/',
getKategori = function(callback) {
getSimpleJson("kategori", serviceBaseCrm, callback);
},
getLand = function(callback) {
getSimpleJson("land", serviceBaseCrm, callback);
};
return {
GetKategori: getKategori,
GetLand: getLand
};
}();
And here is my test:
describe("mb.kontaktViewModel.js", function () {
var server,
kontaktViewModel,
testData = {
land: ['{"Kode": "null", "Id": "e7ae76c0-3598-e311-8270-24fd526b95fb", "Navn": "Chile" },{"Kode": "null", "Id":"d4ae76c0-3598-e311-8270-24fd526b95fb", "Navn":"Mongolia"}'],
kategori: ['{"Id":"297f66b2-2898-e311-8270-24fd526b95fb", "Navn": "Kunde"},{"Id":"2a7f66b2-2898-e311-8270-24fd526b95fb", "Navn":"Leverandør"}'],
dummyModel: { Navn: "En kontakt", Nummber: 10005, OrgNr: null, Id : 10001 }
};
beforeEach(function() {
server = sinon.fakeServer.create();
kontaktViewModel = MB.KontaktViewModel;
});
afterEach(function() {
server.restore();
});
describe("when viewmodel's loadKontakt is called", function () {
it("should populate land with data from server", function () {
server.respondWith("GET", "/crm/kontakt/land", [200, { "Content-Type": "application/json" }, JSON.stringify(testData.land)]);
server.respondWith("GET", "/crm/kontakt/kategori", [200, { "Content-Type": "application/json" }, JSON.stringify(testData.kategori)]);
kontaktViewModel.loadKontakt(testData.dummyModel);
server.respond();
expect(kontaktViewModel.kontakt().land()).toBe(JSON.stringify(testData.land));
});
});
});
Make sure the actual URLs sent are exactly:
/crm/kontakt/land
/crm/kontakt/kategori
You can have a look at the browser console (eg: in Chrome) in the Devtools and see if you're catching it correctly. If you have other strings in your URL you can always match with RegEx. Example, if you want to check if a URL starts with the string you had specified you can use:
server.respondWith("GET", /^\/crm\/kontakt\/kategori/, [200, { "Content-Type": "application/json" }, JSON.stringify(testData.kategori)]);
Otherwise, go ahead in the same devtools and put breakpoints and see what JSON you're getting back.
Finally, I usually like to to set the server to server.autoRespond = true on my beforeEachso you don't have to use the server.respond in each of your tests.

Unit test of $cacheFactory removeAll() in service failing in Angular 1.2.0 but working in 1.0.7

I have a unit test for an Angular service in which I test that a cache $cacheFactory is cleared after a call has been made for a save() method that does an http post to the backend. In 1.0.7 this test passed in Karma and Jasmine Specrunner.html, but after migrating to Angular 1.2.0 it fails. I have not changed any code in the service or in the spec file. The cache is cleared in production when I check it manually. Any ideas?
EDIT: Plunk of the error in action: http://plnkr.co/edit/1INhdM
The error message is:
Field service save() should clear field array from cache.
Expected 2 to be 1.
Error: Expected 2 to be 1.
at new jasmine.ExpectationResult (http://localhost:1234/js/test/lib/jasmine/jasmine.js:114:32)
at null.toBe (http://localhost:1234/js/test/lib/jasmine/jasmine.js:1235:29)
at http://localhost:1234/js/test/spec/field-serviceSpec.js:121:25
at wrappedCallback (http://localhost:1234/js/angular-1.2.0.js:10549:81)
at http://localhost:1234/js/angular-1.2.0.js:10635:26
at Scope.$eval (http://localhost:1234/js/angular-1.2.0.js:11528:28)
at Scope.$digest (http://localhost:1234/js/angular-1.2.0.js:11373:31)
at Scope.$delegate.__proto__.$digest (<anonymous>:844:31)
at Scope.$apply (http://localhost:1234/js/angular-1.2.0.js:11634:24)
at Scope.$delegate.__proto__.$apply (<anonymous>:855:30)
The service I am testing:
angular.module('services.field', [])
.factory('Field', ['$http', '$cacheFactory', function ($http, $cacheFactory) {
var fieldListCache = $cacheFactory('fieldList');
var Field = function (data) {
angular.extend(this, data);
};
// add static method to retrieve all fields
Field.query = function () {
return $http.get('api/ParamSetting', {cache:fieldListCache}).then(function (response) {
var fields = [];
angular.forEach(response.data, function (data) {
fields.push(new Field(data));
});
return fields;
});
};
// add static method to retrieve Field by id
Field.get = function (id) {
return $http.get('api/ParamSetting/' + id).then(function (response) {
return new Field(response.data);
});
};
// add static method to save Field
Field.prototype.save = function () {
fieldListCache.removeAll();
var field = this;
return $http.post('api/ParamSetting', field ).then(function (response) {
field.Id = response.data.d;
return field;
});
};
return Field;
}]);
The unit test that is failing:
'use strict';
describe('Field service', function() {
var Field, $httpBackend;
// load the service module
beforeEach(module('services.field'));
// instantiate service
beforeEach(inject(function(_Field_, _$httpBackend_) {
Field = _Field_;
$httpBackend = _$httpBackend_;
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
describe("save()", function() {
it('should clear field array from cache', function () {
var firstMockData = [{ Alias: 'Alias 1' }, { Alias: 'Alias 2' }];
var secondMockData = [{ Alias: 'Alias 3' }];
var newField = new Field({});
var counter = 0;
$httpBackend.when('GET', 'api/ParamSetting').respond(function () {
// return firstMockData on first request and secondMockdata on subsequent requests
if (counter === 0) {
counter++;
return [200, firstMockData, {}];
} else {
return [200, secondMockData, {}];
}
});
$httpBackend.when('POST', 'api/ParamSetting').respond({});
// query fields
Field.query();
// save new field
newField.save();
// query fields again
Field.query().then(function (data) {
expect(data.length).toBe(secondMockData.length);
expect(data[0].Alias).toBe(secondMockData[0].Alias);
});
$httpBackend.flush();
});
});
});
The answer is that I am erroneously expecting asynchronyous requests to return responses in a particular order, and that my requests are cached until I call $httpBackend.flush() which would lead to .query() only being called once. To make it work, one can make the calls synchronous by adding another flush after the first query() call: http://plnkr.co/edit/MzuplQnkQunDyvy6vCvy?p=preview
The following code will allow you to mock out the $cacheFactory in your unit tests. The $provide service will allow the service dependency injection to use your $cacheFactory instead of the default $cacheFactory.
var cache, $cacheFactory; //used in your its
beforeEach(function(){
module(function ($provide) {
$cacheFactory = function(){};
$cacheFactory.get = function(){};
cache = {
removeAll: function (){}
};
spyOn(cache, 'removeAll');
spyOn($cacheFactory, 'get').and.returnValue(cache);
$provide.value('$cacheFactory', $cacheFactory);
});
});
describe('yourFunction', function(){
it('calls cache.remove()', function(){
yourService.yourFunction();
expect(cache.remove).toHaveBeenCalled();
});
});

Categories