Using Protractor: Switch to iframe using browser.switchTo().frame - protractor

So I have already written the testing script which:
1) Logs into the application framework, then
2) Clicks menu to launch the app which I am testing ("MyAwesomeApp.html" for this post)
And my main problem is: In navpanel-spec.js below, I want to target the https://server/apps/Default.aspx?r=1 URL, then click within the iframe where MyAwesomeApp is running.
**** ERROR Trying to switch to the iframe this way, but it does NOT work:
browser.switchTo().frame(element(by.id('1')).getWebElement());
Error in cmd prompt:
Started
[15:43:29] E/launcher - No element found using locator: By(css selector, *[id="\31 "])
...
sat-navpanel-spec.js:52:24)
So there are two URLs going on here:
1) https://server/apps/Default.aspx?r=1 (the main app framework with menu system in top nav).
2) https://server/apps/MyAwesomeApp.html (the web app which the test script launches within the <iframe> tag.
The html looks like this, where the application renders within the <iframe> :
<body>
<div id="top">
<!-- top nav menu systems rendered here -->
</div>
<div id="middle">
<div id="m1">
<div id="m2" class="hidden">
<div id="m3">
<div id="right" class="hidden">
<div>
<div id="frame_holder" style="height: 940px;">
<iframe style="width: 100%; height: 100%;" name="1" id="1" src="https://server/apps/MyAwesomeApp.html">
</iframe>
</div>
</div>
</div>
</div>
<div id="left" style="display: none;"></div>
</div>
</div>
</div>
</body>
In my Protractor.config.js file I have a few specs :
specs: [
'spec/login.js',
'spec/launch-awesome-app.js',
'spec/navpanel-spec.js',
'spec/another-spec.js',
'spec/yet-another-spec.js'
]
login.js and launch-awesome-app.js work fine. They log into the menu system, then click thru the menus in order to launch myAwesomeapp - no problem.
MY PROBLEM:
In navpanel-spec.js I want to target the https://server/apps/Default.aspx?r=1 URL, then click within the iframe where MyAwesomeApp is running.
However, it is NOT selecting any of my elements.
If I target https://server/apps/MyAwesomeApp.html in navpanel-spec.js, of course it launches a new browser window and runs the test just fine.
Here's my navpanel-spec.js test spec:
describe('Testing My Awesome App', function () {
var panelObj = new PanelObjects();
var urlDefault = 'https://server/apps/Default.aspx?r=1';
var urlApp = 'https://server/apps/MyAwesomeApp.html';
browser.get(urlApp); // Runs my AwesomeApp tests okay, HOWEVER it launches a new browser window.
browser.get(urlDefault); // Launches app framework with top nav menus and embedded <iframe>,
// HOWEVER I cannot select iframe and successfully run tests here.
beforeEach(function () {
browser.sleep(5000);
browser.waitForAngular();
});
// USE-CASE OBJECT !!
var items = browser.params.useCaseJsonFile["navigatePanels"];
browser.getAllWindowHandles().then(function (handles) {
handles.map(function (win, idx) {
browser.driver.getCurrentUrl().then(function (curr) {
if (curr.indexOf('Default.aspx') >= 0) {
browser.driver.switchTo().window(handles[idx]);
}
});
});
});
browser.switchTo().frame(element(by.id('1')).getWebElement());
var testId = element(by.id('middle'));
console.log(testId);
items.map(function (item) {
if (item.enableTest) {
var specItem = it(item.name, function () {
console.log('------------------------------');
console.log('---- ' + item.describe);
browser.waitForAngular();
// select panels, etc..
panelObj.panelClick(item.panelName).then(function () {
// ...
});
panelObj.getPanelText(item.panelName).then(function (title) {
expect(title).toContain(item.panelTitle);
});
});
}
});
});
UPDATE
var LoginObjects = require('../pageObjects/login-objects.js');
describe('Testing My Awesome App', function () {
var panelObj = new PanelObjects();
var loginObj = new LoginObjects();
//var urlDefault = 'https://server/apps/Default.aspx?r=1';
//browser.get(urlApp); // Runs my AwesomeApp tests okay, HOWEVER it launches a new browser window.
browser.ignoreSynchronization = true;
// LOGIN AND LAUNCH APP !!!
loginObj.Login();
loginObj.Launch();
beforeEach(function () {
browser.sleep(5000);
browser.waitForAngular();
});
// USE-CASE OBJECT !!
var items = browser.params.useCaseJsonFile["navigatePanels"];
// SWITCH TO iframe ELEMENT
loginObj.switchWindowAndFrame();
items.map(function (item) {
if (item.enableTest) {
var specItem = it(item.name, function () {
console.log('------------------------------');
console.log('---- ' + item.describe);
browser.waitForAngular();
// select panels, etc..
panelObj.panelClick(item.panelName).then(function () {
// ...
});
panelObj.getPanelText(item.panelName).then(function (title) {
expect(title).toContain(item.panelTitle);
});
});
}
});
});
and my page objects :
module.exports = function(){
this.Login = function(){
var url = browser.params.loginUrl;
browser.driver.get(url);
browser.sleep(200);
var userName = browser.params.credential.userId;
var password = browser.params.credential.password;
element(by.id('username')).clear().then(function(){
element(by.id('username')).sendKeys(userName);
element(by.id('password')).sendKeys(password);
});
browser.sleep(1000);
var that = this;
var submitElement = element(by.id('bthLogin'));
submitElement.click().then(function () {
browser.getAllWindowHandles().then(function (handles) {
// LOGIN MESSAGE WINDOW
browser.driver.getCurrentUrl().then(function(curr){
if (curr.indexOf('LoginMsg.aspx') >= 0){
// Do we really need to close the login successful browser ???
browser.driver.close();
}
});
browser.driver.switchTo().window(handles[1]);
});
});
},
this.Launch = function(){
var sel = '#TheMenu1 > ul > li:first-child';
var elem = element(by.css(sel));
elem.click().then(function(){
browser.sleep(1000);
var elem2 = element(by.cssContainingText('.rmLink', 'The First Menu Item'));
elem2.click();
// Select menu item; sleep before attempting to click().
var subElem = element(by.cssContainingText('.rmLink', 'My Awesome App'));
browser.sleep(1000);
subElem.click();
browser.waitForAngular();
});
},
this.switchWindowAndFrame = function(){
browser.getAllWindowHandles().then(function (handles) {
handles.map(function(win, idx){
browser.driver.getCurrentUrl().then(function(curr){
if (curr.indexOf('Default.aspx') >= 0){
browser.driver.switchTo().window(handles[idx]);
}
});
});
});
browser.switchTo().frame(element(by.css('[name="1"]')).getWebElement());
}
};

As mentioned in the comments above, protractor has a bug which prefixes '\3' to your id element with number.
The temporary way is to change you locator. :P

Related

File upload inside window.addEventListener

My brain's hurting. After my page loads, I get some HTML. This is a stripped-down version:
window.addEventListener('load', () => {
if (window.location.pathname === '/profile' && Cookies.get('token')) {
axios.get('/api/profile-info').then(res => {
const member = res.data.member
const memberInfo = `
<form enctype="multipart/form-data" id="uploadProfilePictureForm">
<input type="file"/>
<button onclick="uploadPicture(event)">Upload</button>
</form>
`;
})
}
})
I then handle the onclick event:
const uploadPicture = (event) => {
event.preventDefault()
const form = document.getElementById('uploadProfilePictureForm')
console.log(form) // Just shows the HTML form
}
This handler is placed before window.addEventListener
The file name appears on the page, but after clicking "Upload", it won't show in the console (which I plan to send to my server).
How do I allow an onclick event to handle a file upload?
Solved
Inside window.addEventListener(), I used a simple input tag:
<input type="file" id="fileUpload" onchange="uploadPicture()"/>
Then, outside this event listener, I defined the uploadPicture() function:
function uploadPicture() {
var FD = new FormData()
var fileInput = document.getElementById('fileUpload')
FD.append("pictureFile", fileInput.files[0])
const data = FD.entries().next().value
console.log('data\n', data) // This is the FormData array
}

Form - new page on submit button

Last year i build a form for one of our costumers, when visitors submitted the form they
got a message on the same page. But now he asks me if it is possible to
make a succes page if the form is filled in correctly.
I can't make it work. It's a bit out of my league.
So i hope anyone of you can help me out!
$(document).ready(function() {
$("#ajax-contact-form").submit(function() {
$('#load').append('<center><img src="ajax-loader.gif" alt="Currently Loading" id="loading" /></center>');
var fem = $(this).serialize(),
note = $('#note');
$.ajax({
type: "POST",
url: "contact/contact2.php",
data: fem,
success: function(msg) {
if ( note.height() ) {
note.slideUp(500, function() { $(this).hide(); });
}
else note.hide();
$('#loading').fadeOut(300, function() {
$(this).remove();
// Message Sent? Show the 'Thank You' message and hide the form
result = (msg === 'OK') ? '<div class="success">Uw bericht is verzonden, we nemen z.s.m. contact met u op!</div>' : msg;
var i = setInterval(function() {
if ( !note.is(':visible') ) {
note.html(result).slideDown(500);
clearInterval(i);
}
}, 40);
}); // end loading image fadeOut
}
});
return false;
});
<form id="ajax-contact-form" target="_blank" method="post" action="javascript:alert('success!');" >
Instead of displaying the "success" message, redirect to a new page:
window.location = successPageUrl;
Just redirect to success page after ajax success.

Remote Datasource and Remote Views + MVVM

I am trying to separate my Views and ViewModels in a Kendo Mobile app (ie. not MVC). I have a remote datasource in a ViewModel and cannot get it to work - I am sure it is something simple (I can't find a Kendo example that uses a Remote DataSource in a ViewModel - it is all inline. (http://demos.telerik.com/kendo-ui/web/mvvm/remote-binding.html, http://docs.telerik.com/kendo-ui/getting-started/framework/datasource/overview)
It just shows this "function (e){var n=this;return e===t?n._data:(n._data=this._observe(e),n._ranges=[],n._addRange(n._data),n._total=n._data.length,n._process(n._data),t)}" and not the actual data.
games.html View
<div id="tabstrip-home"
data-role="view"
data-title="Games"
data-model="app.gamesService.viewModel">
<ul class="games-list"
data-bind="source: gamesDataSource"
data-template="template">
</ul>
</div>
<script type="text/x-kendo-template" id="template">
<div class="product">
<h3>#:ProductName#</h3>
<p>#:kendo.toString(UnitPrice, "c")#</p>
</div>
</script>
games.js ViewModel
(function (global) {
    var GamesViewModel, app = global.app = global.app || {};
 
    GamesViewModel = kendo.data.ObservableObject.extend({
                                                            gamesDataSource: new kendo.data.DataSource({
                                                                                                           transport: {
                                                                    read: {
                                                                                                                   url: "http://demos.telerik.com/kendo-ui/service/Products",
                                                                                                                   dataType: "jsonp"
                                                                                                               }
                                                                }
                                                                                                       })
                                                             
                                                        });
    app.gamesService = {
        viewModel: new GamesViewModel()
    };
})(window);
I found an example and managed to get this working, although the javascript is a little different. I'll have to read up on
(function (global) {
var GamesViewModel,
app = global.app = global.app || {};
GamesViewModel = kendo.data.ObservableObject.extend({
gamesDataSource: null,
init: function () {
var that = this,
dataSource;
kendo.data.ObservableObject.fn.init.apply(that, []);
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "http://demos.telerik.com/kendo-ui/service/Products",
dataType: "jsonp"
//ProductID":1,"ProductName":"Chai","UnitPrice":18,"UnitsInStock":39,"Discontinued":false
}
}
});
that.set("gamesDataSource", dataSource);
}
});
app.gamesService = {
viewModel: new GamesViewModel()
};
})(window);

AngularJS ignores form submit

I'm using AngularJS v1.2.13 to create a page with a form which will download a user's file on click.
I'm using $sce to enable the injection of the file URL which works fine.
However, the loading of the resource disables the form submit. I'm sure it has to do with the resource load because when I remove the load and hardcode the url it works fine. I've also created a JSFiddle without it and have not been able to reproduce the problem there.
Any ideas on why this is happening and how it can be fixed?
HTML:
<div ng-controller="viewProfileController" data-ng-init="findOne();">
<form method="get" action="{{downloadFileURL}}">
<button type="submit" class="no-button comment-small" >
Download File
</button>
</form>
</div>
Controller:
'use strict';
angular.module('bop.viewProfile').controller('viewProfileController', [
'$scope', 'Users', '$sce', '$routeParams',
function($scope, Users, $sce, $routeParams) {
$scope.downloadFileURL = '';
// Find current user
$scope.findOne = function() {
Users.get({
userId: $routeParams.userId
}, function(user) {
$scope.user = user;
$scope.downloadFileURL = $sce.trustAsResourceUrl($scope.user.file.url);
});
};
}]);
Users Service:
var userServices = angular.module('bop.users', ['ngResource']);
userServices.factory('Users', ['$resource', function($resource) {
return $resource(
'users/:userId',
{ userId: '#_id' },
{ update: { method: 'PUT' } }
);
}]);

Display Media Uploader in Own Plugin on Wordpress 3.5

I have little problem with Media Uploader in new WordPress 3.5. I created own plugin which is upload the picture. I'm using this code JS:
<script type="text/javascript">
var file_frame;
jQuery('.button-secondary').live('click', function( event ){
event.preventDefault();
if ( file_frame ) {
file_frame.open();
return;
}
file_frame = wp.media.frames.file_frame = wp.media(
{
title: 'Select File',
button: {
text: jQuery( this ).data( 'uploader_button_text' )
},
multiple: false
}
);
file_frame.on('select', function() {
attachment = file_frame.state().get('selection').first().toJSON();
jQuery('#IMGsrc').val(attachment.url);
});
file_frame.open();
});
</script>
The code works fine, but unfortunately forms appears incomplete. When I select any picture doesn't show me 'Attachment Display Settings' on right side. I don't know why. I try add options to media:
displaySettings: true,
displayUserSettings: true
But it also doesn't work.
Does the page have the <script type="text/html" id="tmpl-attachment-details">... template in the source? If not, you'll need to call wp_print_media_templates(), to write the styles from wp-includes/media-template.php
This is the code I use. Source: http://mikejolley.com/2012/12/using-the-new-wordpress-3-5-media-uploader-in-plugins/ It seems to work pretty well, but the sidebar on the left is missing. (Intentional, but I don't want it anyways).
<?php wp_enqueue_media(); ?>
<script>
function showAddPhotos() {
// Uploading files
var file_frame;
// event.preventDefault();
// If the media frame already exists, reopen it.
if ( file_frame ) {
file_frame.open();
return;
}
// Create the media frame.
file_frame = wp.media.frames.file_frame = wp.media({
title: jQuery( this ).data( 'uploader_title' ),
button: {
text: jQuery( this ).data( 'uploader_button_text' ),
},
multiple: false // Set to true to allow multiple files to be selected
});
// When an image is selected, run a callback.
file_frame.on( 'select', function() {
// We set multiple to false so only get one image from the uploader
attachment = file_frame.state().get('selection').first().toJSON();
// Do something with attachment.id and/or attachment.url here
});
// Finally, open the modal
file_frame.open();
}
</script>