Testing local methods containing service calls using Jasmine - angularjs

I am facing an issue with testing a local method in my Angular JS controller.
I need to test retrieveRuleDetails method which contains a service call, but not able to proceed. Please help to test the below code:
var retrieveRuleDetails = function(feeId, ruleId) {
$rootScope.triggerLoading(true);
FeesRulesService.getRule(feeId, ruleId)
.then(getRuleSuccess)
.catch(getRuleFail);
};

I think best would be to pass FeesRulesService as a paramter - a spy in jasmine
and than to test getRule is invoked
FeesRulesServiceMock= {
getRule: function(feeId,ruleId) {
}
};
spyOn(FeesRulesServiceMock, 'getRule');
retrieveRuleDetails(feeId,ruleId,FeesRulesServiceMock)
it("bla bla",function(){
expect(FeesRulesServiceMock.getRule).toHaveBeenCalled();
expect(FeesRulesServiceMock.getRule).toHaveBeenCalledWith(feeId,ruleId);
});

Related

Testing code that uses document.body.querySelectorAll

Trying to test a directive that does the following:
var inputs = angular.element(document.body.querySelectorAll('input[ng-model]', elem));
// [code relying on found elements]
Running inside karma/jasmine/phantomjs, this fails because it seems that document returns the document that contains the test, rather than the compiled template. Is there some way to mock this functionality so it works as expected (for my use case) or some other way to query for those elements?
PS: The elements that need to be located are in no known relation to the element that the directive is applied to.
You can use $document instead of document then mock it in your tests.
See Angular js unit test mock document to learn how to mock $document.
The last update in this answer did the trick for me he basically is using the $document service, which is like a wrapper over jQuery and then you can append elements to the body directly and test them:
I'll quote his answer:
UPDATE 2
I've managed to partially mock the $document service so you can use
the actual page document and restore everything to a valid state:
beforeEach(function() {
module('plunker');
$document = angular.element(document); // This is exactly what Angular does
$document.find('body').append('<content></content>');
var originalFind = $document.find;
$document.find = function(selector) {
if (selector === 'body') {
return originalFind.call($document, 'body').find('content');
} else {
return originalFind.call($document, selector);
}
}
module(function($provide) {
$provide.value('$document', $document);
});
});
afterEach(function() {
$document.find('body').html('');
});
Plunker: http://plnkr.co/edit/kTe4jKUnypfe6SbDECHi?p=preview
The idea is to replace the body tag with a new one that your SUT can
freely manipulate and your test can safely clear at the end of every
spec.

Testing a filter used within a controller function

I have the following test case:
it('should return id if the post is successful',function(){
var result = {
id : "123"
};
ctrl.saveCallback(result);
expect(ctrl.method.id).to.equal("123");
});
Where ctrl.saveCallback copies the result.id into the method.id on the ctrl and then shows the success banner. On the success banner, we are using the translate filter to translate the message before showing it.
Function:
.....
ctrl.method.id = result.id;
magicallyShowOnScreen($filter('translate')('MESSAGES.SUCCESS'));
....
magicallyShowOnScreen is a service that shows whatever string we pass onto the screen, and that has been injected into beforeEach.
Can someone please point in the right direction as to how should I test or mock out this $filter('translate') ?
Preface: I'm not familiar with Mocha.js or how one would create spies however you would still inject them or similar mock objects the same way as you would for other testing frameworks.
Below is a Jasmine example, I hope it helps.
When you bootstrap your module (using the module / angular.mocks.module) function, you should provide your own version of $filter which should be a mock / spy that returns another mock / spy. For example
var $filter, filterFn;
beforeEach(module('myModule', function($provide) {
$filter = jasmine.createSpy('$filter');
filterFn = jasmine.createSpy('filterFn');
$filter.and.returnValue(filterFn);
$provide.value('$filter', $filter);
});
Then, in your test, you can make sure $filter is called with the right arguments, eg
expect($filter).toHaveBeenCalledWith('translate');
expect(filterFn).toHaveBeenCalledWith('MESSAGE.SUCCESS');
expect(magicallyShowOnScreen).toHaveBeenCalled(); // assuming this too is a spy

How to avoid code duplication in AngularJS Jasmine tests

I'm part of a team that's been working on angularjs for quite a while now and our unit tests consist of files which contain both the test logic and provider mocks of each component that tested element relies on.
This is leading to more and more code duplication, can anyone recommend an angular-ey method whereby we could maintain a test infrastructure, mock a controller or service once and be able to inject that mocked service into other tests as required?
Edit The code I'm working with is proprietary but for an example consider you have 10 or 15 services which retrieve data via HTTP requests, format the data in different ways and return that data. One example might return arrays of data so in each file which relies on the service we would have initialising code like the following ( cut down and altered so please ignore any typos or other mistakes )
myDataService: {
getDataParsedLikeY: {
[{obj1},{obj2}...]
},
getDataParsedLikeX: {
[{obja},{objb}...]
}
beforeEach(angular.mock.module('myModule'));
beforeEach(angular.mock.inject(function(myDataService) {
myDataService = function( functionName ) {
return myDataService[functionName];
}
spyOn(myDataService).and.callThrough();
})
}
If you are looking for a way not to declare same mock codes in every test files, I would suggest something like below although I'm not sure this is angular-way or not.
[1] write the code to declare your mock services like below only for unit test and import after angular-mocks.js
In your-common-mocks.js(you can name the file as you like)
(function(window){
window.mymock = {};
window.mymock.prepare_mocks = function(){
module(function($provide) {
$provide.service('myDataService', function(){
this.getDataParsedLikeY = function(){
return 'your mock value';
};
});
});
};
})(window);
If you use karma, you could write like this to import the file in karma.conf.js.
files: [
...
'(somedirctory)/angular-mocks.js',
'(somedirctory)/your-common-mocks.js'
...
]
[2] use mymock.prepare_mocks function in your test files.
describe('Some Test', function() {
beforeEach(mymock.prepare_mocks);
it('getDataParsedLikeY', inject(function(myDataService){
expect('your mock value', myDataService.getDataParsedLikeY());
As a result of above, you have to write your mock code just one time and share the mock code in your every test files. I hope this could suggest you something to achieve what you want.
If your jasmine version is 2.x, you can write test code like below without writing mock service.
spyOn(YourService, 'somemethod').and.returnValue('mock value');
In jasmine 1.3 you need to adjust little bit.
spyOn(YourService, 'somemethod').andReturn('mock value');
I hope this could help you.

Access local variable inside function and check ng-click in jasmine test with angularjs

Hello I have following code
myApp.controller('myctrl',function($scope,myservice){
//where testClickEvent is ng-click from partials
$scope.testClickEvent=function(args){
var setArg1=args[0];
var params = {"myarg1":setArg1}
//rest call
myservice.testClickEvent(params).success(function(data){
if(data.res==true)
{
$scope.somevariable="success";
}
}).error(function(error){
$scope.somevariable="failure";
});
}
});
I wanted to test it using jasmine that is
testing ng-click event happened in partial ??
how do i test $scope.somevariable and setArg1 has got proper value
here i have used
spyOn(scope,testClickEvent);
scope.testClickEvent(args);
expect(scope.testClickEvent).toHaveBeenCalledWith(args);
spyOn(myservice,testClickEvent);
myservice.testClickEvent(params);
expect(myservice.testClickEvent).toHaveBeenCalledWith(params);
works but how to access result and async call back result????
Thanks in advance ! Your Help appreciated !
You would need to mock out the call using $httpBackend
https://docs.angularjs.org/api/ngMock/service/$httpBackend
The example from the angular page has the following 2 lines:
$httpBackend.when('GET', '/auth.py').respond({userId: 'userX'}, {'A-Token': 'xxx'}); $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, '');
The first one mocks out the response and responds with whatever object is specified
The second one expects the server to be called with a specified object.
Hope this helps.

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