How can I test $rootScope.$emit event? - javascript

I have below code in abc controller:
$rootScope.$on('selectedItem', function (event, data) {
vm.selectedItem = data;
});
And the caller function is in xyz controller:
function doThis(){
$rootScope.$emit('selectedItem', 'somedata');
}
How can I reproduce or mock this scenario in karma test?

For first controller (abc), where you listen to it using $rootScope.$on, you can first $rootScope.$emit it and $scope.$digest() it. So that you can receive it in $on.
var rootScope;
beforeEach(inject(function(_$rootScope_) {
rootScope = _$rootScope_;
}));
describe("some function", function() {
it("should receive selectedItem with $on", function() {
rootScope.$emit('selectedItem', 'somedata');
$scope.$digest();
expect(vm.selectedItem).toEqual('somedata');
});
});
And for second controller (xyz), You can spy on $rootScope.$emit. And expect it to be called in xyz controller. Like this:
var rootScope;
beforeEach(inject(function(_$rootScope_) {
rootScope = _$rootScope_;
spyOn(rootScope, '$emit');
}));
describe("doThis function", function() {
it("should $emit selectedItem", function() {
vm.doThis(); // or if you use $scope, call it that way
expect(rootScope.$emit).toHaveBeenCalledWith('selectedItem');
});
});

Using Jasmine, it could look like this:
var rootScope;
beforeEach(inject(function($injector) {
rootScope = $injector.get('$rootScope');
spyOn(rootScope, '$emit');
}));
describe("$rootScope event testing", function() {
it("should $emit selectedItem", function() {
expect(rootScope.$emit).toHaveBeenCalledWith('selectedItem');
});
});

Related

Ionic unit test in controller, spyOn not passing

It's a very simple test.. and it's not passing.. If someone can throw some light into this :)
This is the controller code (part of it) that needs to be tested
AppCtrl
$scope.requestAuthorization = function() { requestAuthorization(); };
if ($stateParams.requestAuthorization === true) {
console.log('$stateParams.requestAuthorization');
$scope.requestAuthorization();
}
function requestAuthorization() {
console.log('requestAuthorization()');
// more code here..
}
Test
describe('AppCtrl', function() {
var AppCtrl, $rootScope, $scope, $stateParams;
beforeEach(module('myapp'));
// disable ionic cache to avoid GET errors
beforeEach(module(function($provide, $urlRouterProvider) {
$provide.value('$ionicTemplateCache', function() {});
$urlRouterProvider.deferIntercept();
}));
beforeEach(inject(function($controller, _$rootScope_, _$injector_, _$stateParams_) {
$rootScope = _$rootScope_;
$scope = $rootScope.$new();
$stateParams = _$stateParams_;
AppCtrl = $controller('AppCtrl',{
$scope: $scope
});
spyOn($scope, 'requestAuthorization');
$stateParams.requestAuthorization = true;
}));
it('$stateParams.requestAuthorization should be defined', function() {
expect($stateParams.requestAuthorization).toBeDefined();
});
it('$scope.requestAuthorization should be defined', function() {
expect($scope.requestAuthorization).toBeDefined();
});
// this test is not passing..
it('should call requestAuthorization', function() {
expect($scope.requestAuthorization).toHaveBeenCalled();
});
});
The function is actually being called, I can see the console.log in the console, but it's not passing.
Easy tests, all passing.. except the last one..
Thanks for your time :)
NOTE: There is a $stateParams.requestAuthorization, and a $scope.requestAuthorization. First one is boolean, the other a function, the function is not passing.
In your beforeEach block, define the $stateParams before instanciate the Controller.
beforeEach(inject(function($controller, _$rootScope_, _$injector_, _$stateParams_) {
$rootScope = _$rootScope_;
$scope = $rootScope.$new();
$stateParams = _$stateParams_;
$stateParams.requestAuthorization = true;
AppCtrl = $controller('AppCtrl',{
$scope: $scope,
$stateParams: $stateParams
});
spyOn($scope, 'requestAuthorization');
}));

Angular mocha test not firing success/error

I am currently testing a controller in mocha. The controller has an activate function which should fire success/failure based on the response. I cannot get the failure or success functions to fire during my tests.
viewController.js:
(function() {
'use strict';
angular
.module('app')
.controller('viewCtrl', viewCtrl);
function viewCtrl(Service) {
vm.Service = Service;
activate();
function activate() {
vm.Service.get().then(success, failure);
function success(data) {
if (!data || data == 401) {
failure(data);
}
}
function failure(error) {
if (error) {
console.error("Loading question failed:", error);
vm.Service.set();
}
}
}
}
})();
viewControllerTest.js:
describe('question_view_controller', function() {
var httpBackend, controller;
var expect = chai.expect;
var assert = chai.assert;
var Service = {};
var createController;
beforeEach(function(){
angular.mock.module('ui.router');
angular.mock.module('question');
Service = {
set : sinon.stub(),
get : sinon.stub().returns(Promise.reject({error:{}}));
}
})
beforeEach(inject(function($httpBackend,$controller,$q){
httpBackend = $httpBackend;
createController = function(){
return $controller('ViewCtrl', {
$scope: scope,
Service: Service
});;
}
}));
afterEach(function(){
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
describe('activate', function () {
describe('get.then() error', function(){
beforeEach(function(){
Service.get.returns(Promise.reject({error:{}}))
})
it('should do nothing and setFailedQuestion should be called once', function(){
vm = createController();
scope.$digest();
expect(vm.Service.set.callCount).to.equal('1');
})
})
});
});
If anyone could point out my mistake or provide any insight that would be great. Anymore questions please ask.
UPDATE:
Edited code to reflect danday74's answer. Still not working.
UPDATE:
Edited code to reflect danday74's comment. Still not working.
you will need to call scope digest. you will need to inject $rootScope and then ...
vm = createController();
$rootScope.$digest();
expect(vm.Service.set.callCount).to.equal('1');
$digest() causes the THEN blocks to be executed.
similar approach to $httpBackend.flush() if you have ever used that.

How to test function wrapped in a promis

My ctrl is like this:
(function() {
'use strict';
angular
.module('App')
.controller('DeviceStatesCtrl', DeviceStatesCtrl);
function DeviceStatesCtrl( $rootScope, $scope, $translate,DeviceStatesService) {
var vm = this;
DeviceStatesService.getObject().then(function(response){
vm.init(response);
});
vm.init= function(response){
$translate(['table.title']).then(function(translate){
some stuff here
}));
}
}})();
My jasmine test is like this:
describe('app module', function() {
//var controller = null;
var $controller, $translate,$compile,createController,DeviceStatesService,$translate, scope;
var mockInit= sth;
beforeEach(function () {
module('App');
});
// Provide will help us create fake implementations for our dependencies, do not useful
module(function($provide) {
// Fake StoreService Implementation returning a promise
//nothing works :(
$provide.value('DeviceStatesService', {
getStatesObject: function() {
return {
then: function(callback) {
return callback([{ some: "thing", hoursInfo: {isOpen: true}}]);
}
};
}
});
});
return null;
});
beforeEach(inject(function($controller,$rootScope, _$translate_, _DeviceStatesService_) {
scope = $rootScope.$new();
//for 'controller as' syntax
$controller('DeviceStatesCtrl as deviceStat', {
$scope: scope
});
createController = function(params) {
return $controller("DeviceStatesCtrl as deviceStat", {
$scope: scope,
$stateParams: params || {}
});
};
}));
describe("Unit:Device States controller", function() {
//test init function
it("init function get called correctly", function() {
//spyOn(DeviceStatesService, 'getStatesObject').and.callThrough();
//createController();
//expect(DeviceStatesService.getStatesObject).toHaveBeenCalled();
expect(scope.deviceStat.init).toBeDefined();
//in init, all things are warpped in the $translate
//spyOn(scope.deviceStat, 'init');
scope.deviceStat.init(mockInit);
scope.deviceStat.setChart('All');
//expect(scope.deviceStat.totalNum).toEqual(22);
});
});
});
My question is how to test the init function and the stuff in it? The init function is in a promise, which I do not know how to call it. As my code scope.deviceStat.init(mockInit), it do not work. Another question is in the $translate promise, how to pass parameter in it?
You use the done function, which is a parameter passed to the spec via the jasmine function it.. Example..
describe("My Test set", function() {
it("My Test", function(done) {
doAsync().then(function(result) {
done();
}).catch(function(err) {
fail();
}
}
}
Hope this helps.

Angular directive controller unit test using window.confirm

I am trying to get 100% test coverage for a directive. The directive has a controller with a function that uses the window.confirm method.
'use strict';
(function() {
angular
.module('app')
.directive('buttonToggle', buttonToggle);
function buttonToggle() {
var buttonToggleController = ['$scope', function($scope) {
$scope.toggle = function() {
var confirmResponse = (window.confirm('Are you sure?') === true);
if(confirmResponse) {
$scope.on = !$scope.on;
}
return $scope.on;
};
}];
return {
restrict: 'E',
templateUrl: 'client/modules/buttonToggle/buttonToggle.html',
replace: true,
scope: {
on: '='
},
controller: buttonToggleController
};
}
})();
I have tested to make sure that everything is defined, but I am not able to enter the if statement in the controller's $scope.toggle method.
describe('The buttonToggle directive', function() {
var $compile,
$scope,
btElement = '<button-toggle></button-toggle>',
compiledElement,
window,
confirm,
btElementPath = 'client/modules/buttonToggle/buttonToggle.html',
btController;
beforeEach(module('app'));
beforeEach(module(btElementPath));
beforeEach(inject(function(_$compile_, _$rootScope_, $templateCache, $window) {
$compile = _$compile_;
window = $window;
spyOn(window, 'confirm');
$scope = _$rootScope_.$new();
var template = $templateCache.get(btElementPath);
$templateCache.put(btElementPath, template);
var element = angular.element(btElement);
compiledElement = $compile(element)($scope);
$scope.$digest();
btController = element.controller('buttonToggle', {
$window: window
});
scope = element.isolateScope() || element.scope();
}));
it('should be defined', function() {
expect(compiledElement.html()).toContain('btn');
});
describe('buttonToggle controller', function() {
it('should be defined', function() {
expect(btController).not.toBeNull();
expect(btController).toBeDefined();
});
describe('toggle', function() {
it('should be defined', function() {
expect(scope.toggle).toBeDefined();
});
it('should confirm the confirmation dialog', function() {
scope.toggle();
expect(window.confirm).toHaveBeenCalled();
});
});
});
});
I am guessing it has something to do with mocking the $window service, but I'm not sure if I will be able to test that since it isn't declared globally. So, is the controller's function fully "unit testable"? If not, should I write the directive's controller in a separate file and use angular.module.controller? If yes, then how am I able to test it, or what am I missing?
Use angular's $window service instead of window directly, which is what you are doing in your test but not in your directive.
Then you can mock any of its functions:
spyOn($window, 'confirm').and.returnValue(false);

Karma-Jasmine: How to test ionicModal?

THE SITUATION:
In my Ionic app I am testing the correct opening of a modal.
I have made several attempts, but i am getting the following error:
TypeError: Cannot read property 'then' of undefined
THE FUNCTION:
$scope.open_register_modal = function()
{
$ionicModal.fromTemplateUrl('templates/project_register.html', {
scope: $scope
}).then(function(modal) {
$scope.modal_register = modal;
$scope.modal_register.show();
});
};
THE TEST:
describe('App tests', function() {
beforeEach(module('my_app.controllers'));
beforeEach(inject(function(_$controller_, _$rootScope_)
{
$controller = _$controller_;
$rootScope = _$rootScope_;
$scope = _$rootScope_.$new();
$ionicModal =
{
fromTemplateUrl: jasmine.createSpy('$ionicModal.fromTemplateUrl'),
then : function(modal){} // <--- attempt
};
var controller = $controller('MainCtrl', { $scope: $scope, $rootScope: $rootScope, $ionicModal: $ionicModal });
}));
describe('Modal tests', function()
{
it('should open register modal', function()
{
$scope.open_register_modal();
expect($ionicModal).toHaveBeenCalled();
});
});
});
ATTEMPTS:
These are some of the attempts to initialize $ionicModal:
1.
$ionicModal =
{
fromTemplateUrl: jasmine.createSpy('$ionicModal.fromTemplateUrl'),
then : function(modal){}
};
2.
$ionicModal =
{
fromTemplateUrl: jasmine.createSpy('$ionicModal.fromTemplateUrl'),
then: jasmine.createSpy('$ionicModal.then')
};
3.
$ionicModal =
{
fromTemplateUrl: jasmine.createSpy('$ionicModal.fromTemplateUrl'),
then: jasmine.createSpy('$ionicModal.fromTemplateUrl.then')
};
4.
$ionicModal = jasmine.createSpyObj('$ionicModal', ['show', 'close','fromTemplateUrl']);
But they all give the same error:
TypeError: Cannot read property 'then' of undefined
THE QUESTION:
How can i pass the .then method inside the test?
How can i properly test ionicModal?
I don't know anything about ionic, but I think your mistake is expecting that the method then is part of it. The code
$ionicModal.fromTemplateUrl('templates/project_register.html', {
scope: $scope
}).then(function(modal) {
$scope.modal_register = modal;
$scope.modal_register.show();
});
can be refactor to:
var temp=$ionicModal.fromTemplateUrl(
'templates/project_register.html',
{scope: $scope});
temp.then(function(modal) {
$scope.modal_register = modal;
$scope.modal_register.show();
});
so the method then is part of the object returned by the call to fromTemplateUrl
A solution could be something like:
function fakeTemplate() {
return { then:function(){}}
}
$ionicModal = {
fromTemplateUrl: jasmine.createSpy('$ionicModal.fromTemplateUrl').and.callFake(fakeTemplate)
};

Categories

Resources