How to test $ionicPopup.show - ionic-framework

I have an ionicPopup like so:
function editNotifications() {
var popUp = $ionicPopup.show({
template: '<ion-checkbox ng-repeat="item in vm.notifications" ng-model="item.notification" ng-checked="item.notification">' +
'<span class="notificationsFont">{{item.settingsText}}</span></ion-checkbox>',
title: 'Notification Settings',
scope: $scope,
buttons: [
{
text: 'Cancel',
onTap: function(e) {
vm.notifications = localStorageManager.get('notificationStatus');
}
},
{
text: '<b>Ok</b>',
type: 'button-positive',
onTap: function(e) {
localStorageManager.set('notificationStatus', vm.notifications);
vm.notificationText = "Notifications off";
setNotificationValuesBasedOnUserInput(vm.notifications);
}
}]
});
};
Here is what I have so far;
it('Should edit notifications', function() {
spyOn($ionicPopup, 'show').and.callFake(function() {
return $q.resolve(true);
})
spyOn(localStorageManager, 'set');
controller = createController();
controller.editNotifications();
$scope.$apply();
expect(localStorageManager.set).toHaveBeenCalled();
// expect(localStorageManager.set).toHaveBeenCalledWith('notificationStatus');
});
I basically have no idea how to test this thing. There doesn't seem to be much on the internet. I would think I need to do something in my callFake function but I'm a bit stuck. Anyone ever successfully tested this beast before?

Go through this answer: https://stackoverflow.com/a/52565500/7943457
And modify your code something like this:
function editNotifications() {
var popUp = $ionicPopup.show({
template: '<ion-checkbox ng-repeat="item in vm.notifications" ng-model="item.notification" ng-checked="item.notification">' +
'<span class="notificationsFont">{{item.settingsText}}</span></ion-checkbox>',
title: 'Notification Settings',
scope: $scope,
buttons: [
{
text: 'Cancel',
onTap: function(e) {
return false;
}
},
{
text: '<b>Ok</b>',
type: 'button-positive',
onTap: function(e) {
return true;
}
}]
});
popup.then(function(response){
if(response){ //when response is true
localStorageManager.set('notificationStatus', vm.notifications);
vm.notificationText = "Notifications off";
setNotificationValuesBasedOnUserInput(vm.notifications);
}else{ //when response is false
vm.notifications = localStorageManager.get('notificationStatus');
}
})
};
You can test it like this:
it('Should edit notifications', function() {
spyOn($ionicPopup, 'show').and.callFake(function() {
return $q.resolve(true);
})
spyOn(localStorageManager, 'set');
controller = createController();
controller.editNotifications();
$scope.$apply();
expect(localStorageManager.set).toHaveBeenCalled();
// expect(localStorageManager.set).toHaveBeenCalledWith('notificationStatus');
});
it('Should get notifications', function() {
spyOn($ionicPopup, 'show').and.callFake(function() {
return $q.resolve(false);
})
spyOn(localStorageManager, 'get');
controller = createController();
controller.editNotifications();
$scope.$apply();
expect(localStorageManager.get).toHaveBeenCalled();
// expect(localStorageManager.get).toHaveBeenCalledWith('notificationStatus');
});
Hope it helps.

Related

Ionic Alert: Wait until button is pressed

I have a class Action with it's method do() wherein the IonicAlert is called.
What I want to do now is, that I call something like
Action.do().then( () => { /* do domething */ } );
but only after OK was clicked on the alert.
do(): Promise<boolean> {
let alert = this.alertCtrl.create({
buttons: [{
text: 'OK',
handler: () => {
alert.dismiss().then( () => { /* do something */ });
return false;
}
}]
});
alert.present();
return null;
}
}
I added return null; only to get no error, but of course it's not working.
Any idea, how to solve this? Thanks
PS: I also posted it to the ionic forum: https://forum.ionicframework.com/t/ionic-alert-wait-until-button-is-pressed/67448
Found the solution with the help of this site: https://basarat.gitbooks.io/typescript/content/docs/promise.html
do(): Promise<boolean> {
return new Promise((resolve, reject) => {
let alert = this.alertCtrl.create({
buttons: [{
text: 'OK',
handler: () => {
alert.dismiss().then(() => { resolve(true); });
return false;
}
}]
});
alert.present();
});
}
}
Here a version who can return true or false :
showConfirm(): Promise<boolean> {
return new Promise((resolve, reject) =>{
const confirm = this.alertCtrl.create({
title : 'Are you sure ?',
buttons: [
{
text: 'Yes',
handler:_=> resolve(true)
},
{
text: 'No',
handler:_=> resolve(false)
}
]
}).present();
})
}
To call the promise :
this.showConfirm().then((result) => {
if(result){
// do something
}
})
This works for me
handler: () => {
console.log(this.viewCtrl.dismiss());
}
That code didn't work for me in Ionic4. This did:
presentAlert():Promise<boolean> {
return new Promise((resolve, reject) => {
const ctl = this.alertController;
let alert:any = this.alertController.create({
buttons: [{
text: 'OK',
handler: () => {
ctl.dismiss().then(() => { resolve(true); });
return false;
}
}]
}).then((dlg) => dlg.present());
});
}

How to navigate to another XML page when the user click on message popup button

View1.Controller.js
onClickRUSSIA: function() {
var dialog = new Dialog({
title: 'Default Message',`enter code here`
type: 'Message',
content: new Text({
text: 'Country : RUSSIA \n Contenent : ASIA \n language:RUSSIAN.'
}),
beginButton: new Button({
text: 'OK',
press: function() {
dialog.close();
}
}),
endButton: new Button({
text: 'More Info',
press: function() {
//this.getRouter().navTo("mohan");
var router = sap.ui.core.UIComponent.getRouterFor();
router.navTo("View2");
}
}),
afterClose: function() {
dialog.destroy();
}
});
dialog.open();
},
Component.js
sap.ui.define([
"sap/ui/core/UIComponent",
"sap/ui/Device",
"Test1/model/models"
], function(UIComponent, Device, models) {
"use strict";
return UIComponent.extend("Test1.Component", {
metadata: {
//rootView: "test1.webapp.view.App",
manifest: "json",
routing: {
config: {
viewType: "XML",
viewPath: "test1.webapp.view",
controlId: "rootControl",
controlAggregation: "pages",
//routerClass: "Test1.controller",
transition: "slide"
},
routes: [
{
pattern: "",
name: "default",
view: "view1"
}, {
pattern: "mohan",
name: "view2",
View: "view2"
}
]
// targets: {
// page1: {
// viewName: "View1",
// viewLevel: 0
// },
// page2: {
// viewName: "View2",
// viewLevel: 1
// }
// }
}
},
init: function() {
// call the base component's init function
UIComponent.prototype.init.apply(this, arguments);
jQuery.sap.require("sap.m.routing.RouteMatchedHandler");
jQuery.sap.require("sap.ui.core.routing.HashChanger");
sap.ui.core.UIComponent.prototype.init.apply(this, arguments);
this._router = this.getRouter();
// set the device model
this.setModel(models.createDeviceModel(), "device");
//initlialize the router
this._routeHandler = new sap.m.routing.RouteMatchedHandler(this._router);
this._router.initialize();
}
});
});
You will have to get the router for your controller/view. As this is not your controller inside endButton.press(), you have to use a helper variable that.
You have to give Router.navTo() the name of the route to navigate to. So it has to be view2 instead of View2.
var that = this;
var dialog = new Dialog({
...
endButton: new Button({
text: 'More Info',
press: function() {
var router = sap.ui.core.UIComponent.getRouterFor(that);
router.navTo("view2");
}
}),
...
this.getOwnerComponent().getTargets().display("page1");

How to pass selected Value form Popup to normal controller page in ionic framework

How to pass selected Value form Popup to normal controller page in ionic framework
`$scope.showprofpopup = function()
{
$scope.data = {}
var myPopup = $ionicPopup.show
({
templateUrl: 'templates/popover.html',
title: 'Please Choose Category',
scope: $scope,
buttons: [ { text : 'Cancel' }, { text: 'Select', type: 'button-dark', onTap: function(e) { return $scope.data; } }, ]
});
myPopup.then(function(res)
{
//$scope.create(res.category);
//$state.go('app.userdetails');
//$scope.contactMessage = { text: res };
if(!res.category)
{
$ionicLoading.show({ template: '<ion-spinner icon="android"></ion-spinner>', animation: 'fade-in', showBackdrop: true, maxWidth: 100,showDelay: 50 });
$scope.showprofpopup();
$timeout(function () { $ionicLoading.hide(); }, 3000);
//$ionicPopup.alert({ title: "Please Choose Category" });
}
else
{
$scope.SelectedProfessional = { text: res.category};
//alert(res.category);
$state.go('app.userdetails');
}
});
};`
I want to send the result re.category to app.userdetails page.kindly anyone help me.
using $stateParams
$state.go('app.userdetails',{'category': res.category});

Modal open with angualrjs route

Hey I am working with bootstrap modal and calling it in angularjs. Its working good. Only the problem is that how can I route modal in angularjs routing. My Code:
Inside Controller
var modalInstance = $modal.open({
templateUrl: 'webpages/home/loginModal.html'
});
modalInstance.result.then(function () {
}, function () {
});
Inside Routing
.when('/login', {
templateUrl: function($routeParams) {
return 'sitepages/home/home.html';
},
controller: 'PageViewController',
reloadOnSearch: false
})
Its just example of routing how I am doing it, I need to find routing for modal.
You can use states for this purposes
$stateProvider.state("items.add", {
url: "/add",
onEnter: ['$stateParams', '$state', '$modal', '$resource', function($stateParams, $state, $modal, $resource) {
$modal.open({
templateUrl: "items/add",
resolve: {
item: function() { new Item(123).get(); }
},
controller: ['$scope', 'item', function($scope, item) {
$scope.dismiss = function() {
$scope.$dismiss();
};
$scope.save = function() {
item.update().then(function() {
$scope.$close(true);
});
};
}]
}).result.then(function(result) {
if (result) {
return $state.transitionTo("items");
}
});
}]
});
More details: https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-open-a-dialogmodal-at-a-certain-state
You don't need the routing for it
app.controller("ACtrl", ['$scope','$http', '$log', '$modal',
function($scope, http, $log, $modal){
$scope.OpenModel = function () {
var param = { appId: 1, price: 2.5 };
var modalInstance = $modal.open({
size: 'lg',
backdrop: 'static',
templateUrl: 'webpages/home/loginModal.html',
controller: 'modalCtrl',
resolve: {
data: function () { return param; }
}
});
modalInstance.result.then(function (response) {
//Do whatever you want to do with reponse
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
}
}
///Add your modal control here
app.controller("modalCtrl", ['$scope','$http', '$modalInstance', 'data',
function($scope, http, $modalInstance, data){
// rest of the code goes here
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}
}

Changed values of collection not reflected in backbone.js

When i click on submit button i can't see the changes made to collection although on every click of checkbox change event is fired
//Model
Wine = Backbone.Model.extend({
// Toggle the `IsSelected` state of this todo item.
toggle: function () {
debugger;
this.save({
IsSelected: !this.get('IsSelected')
});
}
});
//Collection
WineCollection = Backbone.Collection.extend({
model: Wine,
url: "http://localhost/Industries/data/data.json"
});
//This is a list view collection and individual List item and here we bind the click event of checkbox and in Submit button here we check the the changed values
WineListView = Backbone.View.extend({
el: $('#wineList'),
initialize: function () {
alert($('#divBtnSubmit'));
wineList.bind("reset", this.render, this);
},
render: function () {
wineList.each(function (wine) {
$(this.el).append(new WineListItemView({ model: wine }).render().el);
}, this);
return this;
}
});
//Submit button
WinedivBtnSubmit = Backbone.View.extend({
el: $('#divBtnSubmit'),
initialize: function () {
this.render();
},
render: function () {
// Load the compiled HTML into the Backbone "el"
var template = _.template($("#save-div").html(), {});
this.$el.append(template);
},
events: {
"click #divBtnSubmit1": "saveWine"
},
saveWine: function () {
debugger;
wineList.each(function (wine) {
alert(wine.get('ID') + '<<>>' + wine.get('IsSelected'));
});
return false;
// alert(this.modelmodels);
}
});
//Indiviual list item
WineListItemView = Backbone.View.extend({
tagName: "li",
template: _.template($('#wine-list-item').html()),
initialize: function () {
},
events:
{
'click .toggle': 'toggleVisible'
},
toggleVisible: function () {
this.model.toggle();
},
render: function (eventName) {
$(this.el).html(this.template(this.model.toJSON()));
return this;
}
});
var AppRouter = Backbone.Router.extend({
routes: {
"": "list",
"wines/:id": "wineDetails"
},
initialize: function () {
},
list: function () {
// this.wineList = new WineCollection();
this.wineListView = new WineListView();
this.btn = new WinedivBtnSubmit();
// wineList.fetch();
},
wineDetails: function (id) {
this.wine = this.wineList.get(id);
this.wineView = new WineView({ model: this.wine });
this.wineView.render();
}
});
wineList = new WineCollection();
wineList.fetch();
// on every click of checkbox this event is fired
wineList.bind("change", function () {
alert('list changed');
});
var app = new AppRouter();
Backbone.history.start();