Jasmine JSON fixtures VS service mocking - angularjs

Assume we have a service which calls api and we use this service to do some logic in a controller.
What is better to use?
user = $injector.get('userSrv');
var myFixture = angular.fromJson(window.__html__['mydata.json']);
$httpBackend.whenGET('url/').respond(myFixture);
user.getGender();
or just using
beforeEach(module(function($provide) {
$provide.service('userSrv', function(){
return {
getGender: function(){
return 'something';
}
}
});
})

Both should be used, but in different tests.
In controller spec, a service is supposed to be mocked, because the unit under test is a controller.
In service spec, http request is supposed to be mocked, because the unit under test is a service (this allows to keep the test synchronous and independent from the backend, it is not possible to perform real requests with ngMock any way).
This allows to unambiguously determine which unit failed when a test becomes red.

Related

Promises are not resolved in Jasmine using Karma

I have a problem with a small karma unit test that should check a simple decryption/encryption service.
The thing is, if I call the following code "manual" (i.e., within my running angular app) everything is fine and I receive the expected test output:
this.encryptDataAsync('Hello World of Encryption','b4b63cd1a64dbef72fefe2eb3e3fc3eb').then((encryptedValue : string) : void => {
console.log('1',encryptedValue);
this.decryptDataAsync(encryptedValue,'b4b63cd1a64dbef72fefe2eb3e3fc3eb').then(function(decryptedValue : string) : void{
console.log('2',decryptedValue);
});
});
As soon as I try to run this Karma/Jasmine unit test
describe('simple encryption/decryption', function() {
var results = '';
beforeEach(function(done) {
_cryptoService.encryptDataAsync('ABC','b4b63cd1a64dbef72fefe2eb3e3fc3eb').then(function (encryptedValue){
console.log('1');
_cryptoService.decryptDataAsync(encryptedValue,'b4b63cd1a64dbef72fefe2eb3e3fc3eb').then(function(decryptedValue){
console.log('2');
results = decryptedValue;
done();
});
});
});
it("check results", function(done){
expect(results).toBe('ABC');
done();
}, 3000);
});
I never reach console.log('1') nor '2'. I can confirm this while debugging the unit test. However, this is the only unit test that fails in the complete suite, so I guess it won't by a problem with modules, etc.
Is there a general problem with my test case? I would have expected that I can use the then functions to handle my test case and, afterwards, call the done() function to invoke the assertion part.
Update/Edit:
The service uses webcrypto as a library. It is complete independent of angular besides being an angular service (so, no variables on scopes, etc)
I needed to call scope.apply since "$q is integrated with the $rootScope.Scope Scope model observation mechanism in angular, which means faster propagation of resolution or rejection into your models and avoiding unnecessary browser repaints, which would result in flickering UI."

Breeze.JS to use angular.js http

I am trying to make Breeze.JS to make use of angular's http service for ajax calls. I followed the the docs (http://www.breezejs.com/documentation/customizing-ajax) and applied it. However it doesn't work.
Further more when I checked breeze source code I saw the following:
fn.executeQuery = function (mappingContext) {
var deferred = Q.defer();
var url = mappingContext.getUrl();
OData.read({
requestUri: url,
headers: { "DataServiceVersion": "2.0" }
},
function (data, response) {
var inlineCount;
if (data.__count) {
// OData can return data.__count as a string
inlineCount = parseInt(data.__count, 10);
}
return deferred.resolve({ results: data.results, inlineCount: inlineCount });
},
function (error) {
return deferred.reject(createError(error, url));
}
);
return deferred.promise;
};
It simply calls OData.read without doing anything about http service. Thus OData makes use of builtin ajax. I don't understand with above code, how it is possible to customize ajax of Breeeze.JS
The problem is that the Breeze OData path does NOT use the Breeze Ajax adapter. Changing the Breeze Ajax Adapter (as the "Breeze Angular Service" does) won't help.
At the moment, both the "OData" and "webApiOData" DataService Adapters delegate to the 3rd party datajs library for AJAX services (and for other OData-related support).
You could replace its odata.defaultHttpClient with a version of your own based on $http. That's not a trivial task. Look here for the source code; it's roughly 160 lines.
I suppose we could write one. It hasn't been a priority.
Until somebody does it or we abandon datajs (not soon if ever), you're stuck with the datajs ajax.
Sorry about that.
p.s. Just about everyone who talks to OData data sources uses the datajs library. Maybe you can talk to the authors of that library and try to get them to support$http.
Quick and dirty hack to simulate $http service
I ran into this issue today. Since the external datajs AJAX methods are used rather than Angular's $http service (as explained by Ward), Breeze queries do not trigger a digest and the models do not get updated.
As with any external-to-angular changes, the simple solution is to wrap any assignments from your queries in a $scope.$apply() function. However, this will quickly clutter up your app so it's a bad idea.
I came up with a quick and dirty hack that so far seems to work well:
I have a dataContextservice which encapsulates all my Breeze queries and exposes methods like getCustomers(), getProducts() etc (inspired by the example on the Breeze site).
When any of these data-access methods completes (ie the promise resolves), I call a triggerAngularDigest() method.
This method simple calls $rootScope.$apply() inside a $timeout().
The $timeout() causes Angular to run the digest on the next tick, i.e. after the data from your Breeze query has been assigned to your models.
All your models update just like when you use $http, no need to call $apply() in your controllers.
Simplified version:
function dataContext($rootScope, $timeout, breeze) {
// config of entity manager etc snipped
return {
getCustomers: function () {
return breeze.EntityQuery.from('Customers')
.using(manager)
.execute()
.then(function(data) {
triggerAngularDigest(); // <-- this is the key
return data;
});
}
};
function triggerAngularDigest() {
$timeout(function() {
$rootScope.$apply();
}, 0);
}
}
myApp.factory('dataContext', dataContext);
Then:
// some controller in your app
dataContext.getCustomers().then(function(data) {
scope.customers = data;
});

AngularJS Mock - expect vs when

What is the difference between expect and when in the ngMock AngularJS module?
They both provide a response, so when would you use one over the other?
I read the docs at angularJS.com, but it was not very clear to me.
This is the service I want to test using Jasmine, so should I expect a endpoint was called, or should I bank on a known value being returned?
(function () {
'use strict';
var app = angular.module('cs');
app.service('PlateCheckService', ['$http', function ($http) {
return {
checkPlate: function (plateNumber) {
return $http.post('PlateCheck/Index', {
plateNumber: plateNumber
}).then(function (response) {
return {
message: response.data.VehicleAtl === null ? 'Clean' : 'Hot',
alertClass: response.data.VehicleAtl === null ? 'alert-success' : 'alert-danger'
};
});
}
};
}]);
}());
The explanation in the doc is crystal clear to me:
Request Expectations vs Backend Definitions
Request expectations provide a way to make assertions about requests made by the application and to define responses for those requests. The test will fail if the expected requests are not made or they are made in the wrong order.
Backend definitions allow you to define a fake backend for your application which doesn't assert if a particular request was made or not, it just returns a trained response if a request is made. The test will pass whether or not the request gets made during testing.
So, if you use when(), you can do any request, in any order, and the test won't fail. If you use expect(), then the test will fail if the backend doesn't receive the expected requests, in the same order as the expected ones.

angularJS unit testing where run contains a HTTP request?

I am fairly new to AngularJS and am trying to learn some best practices. I have things working, but would like to start adding some unit tests to my modules and controllers. The first one I am looking to tackle is my AuthModule.
I have an AuthModule. This Module registers a Factory called "AuthModule" and exposes things like "setAuthenticatedUser" and also fields like "isLoggedIn" and "currentUser". I think this is a fairly common pattern in an AngularJS application, with some variations on the specific implementation details.
authModule.factory(
'AuthModule',
function(APIService, $rootScope) {
var _currentUser = null;
var _isLoggedIn = false;
return {
'setAuthenticatedUser' : function(currentUser) {
_currentUser = currentUser;
_isLoggedIn = currentUser == null ? false : true;
$rootScope.$broadcast('event:authenticatedUserChanged',
_currentUser);
if (_isLoggedIn == false) {
$rootScope.$broadcast('event:loginRequired')
}
$rootScope.authenticatedUser = _currentUser;
$rootScope.isLoggedIn = _isLoggedIn;
},
'isLoggedIn' : _isLoggedIn,
'currentUser' : _currentUser
}
});
The module does some other things like register a handler for the event "loginRequired" to send the person back to the home screen. These events are raised by the AuthModule factory.
authModule.run(function($rootScope, $log, $location) {
$rootScope.$on("event:loginRequired", function(event, data) {
$log.info("sending him home. Login is required");
$location.path("/");
});
});
Finally, the module has a run block which will use an API service I have to determine the current logged in user form the backend.
authModule.run(
function(APIService, $log, AuthModule) {
APIService.keepAlive().then(function(currentUser) {
AuthModule.setAuthenticatedUser(currentUser.user);
}, function(response) {
AuthModule.setAuthenticatedUser(null);
});
});
Here are some of my questions:
My question is how would you setup tests for this? I would think that I would need to Mock out the APIService? I'm having a hard time because I keep getting unexpected POST request to my /keepalive function (called within APIService.keepAlive())?
Is there any way to use $httpBackend in order to return the right response to the actual KeepAlive call? This would prevent me from having to mock-out the API service?
Should I pull the .run() block out which obtains the current logged in user out of the AuthModule and put it into the main application? It seems no matter where I put the run() block, I can't seem to initialize the $httpbackend before I load the module?
Should the AuthModule even be its own module at all? or should I just use the main application module and register the factory there?
Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.angularjs docs
I suggest you take a look at this authentication service, using a service is the way to go.
Hopefully this would help ... Good luck

Angular E2E testing with mocked httpBackend?

A hot discussion raised between me and my boss about Angular E2E testing. according to vojitajina pull request we need to run a server in order to run the e2e tests. So, running e2e test involves a real server, a real server involves DB. This makes test slow.Ok, now the question is how to test e2e without involving a real server ? is there a way to use httpBackend to and the e2e angular API where I can use browser(), element(), select(), for my tests ?
[see edit below] We use a shell script to periodically capture curl requests from our seeded test server. These responses are then returned via $httpBackend.whenGet(...).respond() to intercept and return that data.
So, in our index.html
if (document.location.hash === '#test') {
addScript('/test/lib/angular-mocks.js');
addScript('/test/e2e/ourTest.js');
window.fixtures = {};
addScript('/test/fixtures/tasks/tasks_p1.js');
// the tasks_p1.js is generated and has "window.fixtures.tasks_p1 = ...json..."
addScript('/test/fixtures/tasks/tasks_p2.js');
// the tasks_p2.js is generated and has "window.fixtures.tasks_p2 = ...json..."
addScript('/test/e2e/tasks/taskMocks.js\'><\/script>');
}
ourTest.js
angular.module('ourTestApp', ['ngMockE2E','taskMocks']).
run(function ($httpBackend, taskMocks) {
$httpBackend.whenGET(/views\/.*/).passThrough();
$httpBackend.whenGET(/\/fixtures.*\//).passThrough();
taskMocks.register();
$httpBackend.whenGET(/.*/).passThrough();
});
taskMocks.js
/*global angular */
angular.module('taskMocks', ['ngMockE2E']).
factory('taskMocks', ['$httpBackend', function($httpBackend) {
'use strict';
return {
register: function() {
$httpBackend.whenGET(..regex_for_url_for_page1..).respond(window.fixtures.tasks_p1);
$httpBackend.whenGET(..regex_for_url_for_page2..).respond(window.fixtures.tasks_p2);
}
};
}]);
In a few cases our data is related to the current date; e.g. "tasks for this week", so we massage the captured data in the register() method.
EDIT
We now use Rosie to create factories for our mocked objects. So, no more CURLing test server for expected json responses. index.html no longer loads these ".js" fixtures and the mocks look like:
taskMocks.js
/*global angular */
angular.module('taskMocks', ['ngMockE2E']).
factory('taskMocks', ['$httpBackend', function($httpBackend) {
'use strict';
var tasks_p1 = [ Factory.build('task'), Factory.build('task')],
tasks_p2 = [ Factory.build('task'), Factory.build('task')]
return {
register: function() {
$httpBackend.whenGET(..regex_for_url_for_page1..).respond(tasks_p1);
$httpBackend.whenGET(..regex_for_url_for_page2..).respond(tasks_p2);
}
};
}]);
To answer your question, yes there is a way to do it without involving a real server and you can use $httpBackend to mock responses in e2e tests, but it is not as straightforward as with mocking them in the unit tests. You also need to include angular-mocks.js in the index.html as well as 'ngMockE2E' in app.js.
How to mock an AJAX request?

Resources