How Do I Find the Script SRC in Jasmine - javascript

I am REALLY new to Jasmine and am trying to write a unit test that checks if a URL is constructed properly from variables defined by the environment.
describe('URL is built properly', function() {
var newHead = '<!doctype html>' +
'<html class="no-js" lang="">' +
' <head>' +
' </head>' +
'<body>' +
'</body>' +
'</html>';
beforeEach(function() {
ScratchPad.clear();
ScratchPad.add(newHead);
debugger;
spyOn(newSetup.prototype, 'createNewScript');
});
afterAll(function() {
ScratchPad.clear();
});
it('should build Staging', function() {
window.my.env = 'staging';
window.my = {
newScript: {
enabled: true,
location: 'google-com'
}
};
var options = {
windowWidth: 640
};
this.newScript = new newScriptSetup(options);
var newHTML = ScratchPad.find('script')[0].src;
debugger;
expect(newHTML.src).toEqual('http://my.site.com/google-com/myScript.min.js');
});
});
The problem I seem to be having is that;
expect(newHTML.src).toEqual('http://my.site.com/google-com/myScript.min.js');
this bit of the script isn't getting populated, I've tried debugging it and the var newHead is being created, it's just not being seen by the rest of the unit test... I think. Could someone help me out, I've been looking at it all day :(

var newHTML = ScratchPad.find('script')[0].src;
debugger;
expect(newHTML.src)..
You are already getting the src in newHTML. You are trying to check .src.src with the url you provide. Try this:
var newHTML = ScratchPad.find('script')[0].src;
expect(newHTML).toBe(..

Related

Setting VideoJS Source via Javascript

I'm trying to set the source and type for Video.js dynamically via a JSON object that is retrieved from a remote method call.
radioPlayer = videojs("RadioPlayer");
function RadioListPage() {
$.getJSON(serviceURL + 'rbApp.cfc?method=Radio', function(data) {
$.each(data.DATA, function(index, itemData) {
$('#radioList').append('<div class="play" data-type="' + itemData[4] + '" data-src="' + itemData[3] + '" data-station="' + itemData[1] + '" data-id="' + itemData[0] + '"><img src="' + itemData[2] + '"></div>');
lastIDNumberVideo = itemData[0];
});
$('#radioList .play').click(function() {
var stationObject = new Object();
stationObject.src = $(this).data("src");
stationObject.type = $(this).data("type");
var jsonStr = JSON.stringify(stationObject);
radioPlayer.src(jsonStr);
radioPlayer.play();
});
loading('hide', 100);
});
}
VideoJS will throw an error that the stream isn't valid. However, if I take that jsonStr variable and hard code that value like this radioPlayer.src({"src":"http://wlca-stream.lc.edu:8004/wlca","type":"audio/mpeg"}) it plays with no issue. What am I missing here? Is this not possible to do?
The example code you show provides a JS object to the src() method, yet you're providing JSON. Try providing the object directly to the method.
Also note that I'd suggest you use a delegated event handler instead of binding events in the AJAX callback, which can lead to issues with duplicated events. Try this:
radioPlayer = videojs("RadioPlayer");
$('#radioList').on('click', '.play', function() {
radioPlayer.src({
src: $(this).data("src"),
type: $(this).data("type")
});
radioPlayer.play();
});
function RadioListPage() {
$.getJSON(serviceURL + 'rbApp.cfc?method=Radio', function(data) {
let html = data.DATA.map(item => `<div class="play" data-type="${item[4]}" data-src="${item[3]}" data-station="${item[1]}" data-id="${item[0]}"><img src="${item[2]}"></div>`);
$('#radioList').append(html);
lastIDNumberVideo = data.DATA.slice(-1)[0];
loading('hide', 100);
});
}

Output SharePoint Document Library Files to CSV File Using JavaScript

I’m seeking how to output SharePoint Document Library Files to csv file. I found script that get me almost there, but I can’t figure out how to update the code to export the information to a csv file instead to the console.log() or to an alert(). Everything I tried breaks the code. I review other JavaScript concept that shows the how to add out to CSV but I again the script concept breaks the code I’m trying to modify. The script I am using. In addition, the script output the file names. I like to get help on how I can not only output the file name, but I like to output, modified date, created date, and the link to the file. I hope this is possible and I appreciate any help in achieving this concept. Script I'm using follows below.
jQuery(document).ready(function() {
var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";
$.getScript(scriptbase + "SP.Runtime.js", function() {
$.getScript(scriptbase + "SP.js", function() {
$.getScript(scriptbase + "SP.DocumentManagement.js", createDocumentSet);
});
});
});
var docSetFiles;
function createDocumentSet() {
//Get the client context,web and library object.
clientContext = new SP.ClientContext.get_current();
oWeb = clientContext.get_web();
var oList = oWeb.get_lists().getByTitle("Fact Sheets & Agreements");
clientContext.load(oList);
//Get the root folder of the library
oLibraryFolder = oList.get_rootFolder();
var documentSetFolder = "sites/nbib/ep/Fact%20Sheets/";
//Get the document set files using CAML query
var camlQuery = SP.CamlQuery.createAllItemsQuery();
camlQuery.set_folderServerRelativeUrl(documentSetFolder);
docSetFiles = oList.getItems(camlQuery);
//Load the client context and execute the batch
clientContext.load(docSetFiles, 'Include(File)');
clientContext.executeQueryAsync(QuerySuccess, QueryFailure);
}
function QuerySuccess() {
//Loop through the document set files and get the display name
var docSetFilesEnumerator = docSetFiles.getEnumerator();
while (docSetFilesEnumerator.moveNext()) {
var oDoc = docSetFilesEnumerator.get_current().get_file();
alert("Document Name : " + oDoc.get_name());
console.log("Document Name : " + oDoc.get_name());
}
}
function QueryFailure() {
console.log('Request failed - ' + args.get_message());
}
Sample test script in chrome.
function QuerySuccess() {
//Loop through the document set files and get the display name
var csv = 'Document Name\n';
var docSetFilesEnumerator = docSetFiles.getEnumerator();
while (docSetFilesEnumerator.moveNext()) {
var oDoc = docSetFilesEnumerator.get_current().get_file();
//alert("Document Name : " + oDoc.get_name());
//console.log("Document Name : " + oDoc.get_name());
csv += oDoc.get_name();//+',' if more cloumns
csv += "\n";
}
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
hiddenElement.target = '_blank';
hiddenElement.download = 'DocumentList.csv';
hiddenElement.click();
}

Issues in Uploading File using ajax in IE7 and IE8

I'm trying to upload a file in IE7 and IE8 browser using FileAPI library, but unfortunately it is not working. It is working in all the other browser but not in IE7, IE8 and it is my business requirement to make it work in IE7, IE8 too.
Here is my js code
jQuery(function ($){
$(document)
.on('click', '.imageLabel', function (evt){
imageUploadId = $(this).attr("id").split("_")[1];
previewImage = document.getElementById('previewHolderDiv_' + imageUploadId);
$("#imageError_" + imageUploadId).html("");
errorMessageUl = document.getElementById('imageError_' + imageUploadId);
removeImageIcon = document.getElementById('removeImage_' + imageUploadId);
})
var form = document.forms.vehicleDocumentForm;
var input = form.vehicleImage;
var uploadOpts = {
url: '/save-vehicle-document',
data: {},
name: 'vehicleImage',
activeClassName: 'upload_active'
};
var _onSelectFile = function (evt/**Event*/){
var file = FileAPI.getFiles(evt)[0];
if( file ){
_uploadFile(file, imageUploadId);
}
};
var _uploadFile = function (file){
uploadOpts.data = {"imageId" : imageUploadId};
var opts = FileAPI.extend(uploadOpts, {
files: {},
upload: function (){
form.className += ' '+uploadOpts.activeClassName;
},
complete: function (err, xhr){
//enableSellYourButtons();
form.className = (' '+form.className+' ').replace(' '+uploadOpts.activeClassName+' ', ' ');
var response = JSON.parse(xhr.responseText);
if( response.result == "fail"){
previewImage.html = "";
$("#imageError_" + imageUploadId).html("<li>" + response.message + "</li>");
} else {
$("#imageError_" + imageUploadId).html("");
$("#vehicleImageName_" + imageUploadId).attr("value", response.message);
}
}
});
opts.files[opts.name] = file;
FileAPI.upload(opts);
};
FileAPI.event.on(input, "change", _onSelectFile);
}); // ready
I'm getting an error
SCRIPT445: Object doesn't support this action
File: FileAPI.min.js, Line: 2, Column: 11608
My FileAPI version is 2.0.11
Any help would be greatly appreciated.
Thank you.
According to caniuse, the FileApi is not compatible with IE7/8.

HandlebarsJS Uncaught TypeError: Cannot read property 'url' of undefined

I'm just starting to learn Handlebars.js, I used the Handlebars.js site (http://handlebarsjs.com/expressions.html) to help write this following snippet here:
http://jsfiddle.net/3TxVx/2/
var story = {
url: "www.nytimes.com/colonizemars.html",
text: "We finally colonized mars!"
};
Handlebars.registerHelper('link', function(object) {
return new Handlebars.SafeString(
"<a href='" + object.url + "'>" + object.text + "</a>"
);
});
var theTemplateScript = $("#header").html();
var theTemplate = Handlebars.compile (theTemplateScript);
var temp = theTemplate(story);
console.log(temp);
$(function() {
$(document.body).append (temp);
});
Not sure why I get the following error when I run it:
Uncaught TypeError: Cannot read property 'url' of undefined
Thanks!
Try replacing
registerHelper('link', function(object)
with
registerHelper('link', function(text, url)
From the docs:
Handlebars.registerHelper('link', function(text, url) {
text = Handlebars.Utils.escapeExpression(text);
url = Handlebars.Utils.escapeExpression(url);
var result = '' + text + '';
return new Handlebars.SafeString(result);
});
http://handlebarsjs.com/
Turns out Handlebars is very picky on the format of the data or context. I made the the following change to the story object and it worked.
var data = {
story : {
url: "www.nytimes.com/colonizemars.html",
text: "We finally colonized mars!"
}
};
So now my entire code looks like this:
<script id="header" type="text/x-handlebars-template">
{{{link story}}}
</script>
<script type="text/javascript">
Handlebars.registerHelper('link', function(object) {
return new Handlebars.SafeString("<a href='" + object.url + "'>" + object.text + "</a>"
);
});
var data = {
story : {
url: "www.nytimes.com/colonizemars.html",
text: "We finally colonized mars!"
}
};
var theTemplateScript = $("#header").html();
var theTemplate = Handlebars.compile (theTemplateScript);
var temp = theTemplate(data);
console.log(temp);
$(function() {
$(document.body).append (temp);
});
</script>

calling JQuery HTTP GET request inside javascript function

I will start off by saying I am new to Javascript and JQuery. What I want to accomplish is have a submit button on an HTML page that will call the dbQuery function in my .js file that will print the value of variables to the screen and then add them into a MySQL database.
I need to use the JavaScript variable selectedVisibleValue that is defined in my first function dbQuery The reason I want to do this is because I have four drop downs, three of which are hidden drop downs that are only shown depending on the first non hidden dropdown, only one of the hidden drop downs is ever visible.
I want to work with these variables in my PHP page formPage to do the Database functions. My code is below I want to add the testing1 function into the dbQuery function.
I have tried just copying and pasting it into the dbQuery function but it does not work. I am not trying to work with the selectedVisibleValue in the code below. I am just trying to do some testing with some bogus variables.
var dbQuery = function(){
var description = document.getElementById("jobDescription").value;
var selectedEquip = document.getElementById("equipmentList");
var selectedEquip1 = selectedEquip.options[selectedEquip.selectedIndex].text;
var selectedVisibleValue = $(".unitDropDowns select:visible").val();
document.getElementById("descriptionSummary").innerHTML = "<h3>Description</h3>" + "<p>" + description + "</p>";
document.getElementById("equipmentRan").innerHTML = "<h3>Equipment Ran </h3>" + "<p>" + selectedEquip1 + "</p>" + "<h3>Unit Number</h3>" + "<p>" + selectedVisibleValue + "</p>";
document.getElementById("equipmentRan").style.display = "block";
document.getElementById("descriptionSummary").style.display = "block";
}
var testing1 = function() {
$.get(
"formPage.php",
{paramOne : 123, paramX : 'abc'},
function(data) {
document.getElementById("equipmentRan").innerHTML = ('page content: ' + data);
}
);
}
//cache references to static elements
var jobDescription = $('#jobDescription')
, selectedEquip = $('#equipmentList')
, descriptionSummary = $('#descriptionSummary')
, equipmentRan = $('#equipmentRan')
;
function dbQuery(){
//gather params
var params = {
jobDescription : jobDescription.val(),
selectedEquip1 : selectedEquip.val(),
selectedVisibleValue = $(".unitDropDowns select:visible").val()
}
//show summary
descriptionSummary.html('<h3>Description</h3><p>'+description+'</p></h3>').show();
equipmentRan.html('<h3>Equipment Ran</h3><p>'+selectedEquip1+'</p><h3>Unit Number</h3><p>'+selectedVisibleValue+'</p>').show();
//do a get
$.get('formPage.php',params,function(data) {
equipmentRan.html('page content: ' + data);
}
}
jsFiddle DEMO
Passing variables between functions might come in useful for your project.
HTML:
<div id="theBox"></div>
<button>Press Me</button>
JS
$(document).ready(function() {
// This is some other Do More function, defined prior to the next variable function.
// This is your .get() request.
function doMore(target){
// For the incomming targer, add a class style of a larger font.
$(target).css('font-size', 30);
}
// The main function.
var dbQuery = function() {
// Show dynamic text on the HTML page.
var extra = $('#theBox').html('Dynamic Text Results');
// Run some other function, also... send the private variable in use.
doMore(extra);
};
// The submit button.
$('button').on('click', function() {
// Start the function.
dbQuery();
});
});
Here is the working code:
function dbQuery() {
window.description = document.getElementById("jobDescription").value;
var selectedEquip = document.getElementById("equipmentList");
window.selectedEquip1 = selectedEquip.options[selectedEquip.selectedIndex].text;
window.selectedVisibleValue = $(".unitDropDowns select:visible").val();
testing1();
}
function testing1() {
$(document).ready(function() {
$.get(
"formPage.php",
{paramOne : window.selectedVisibleValue, paramX : window.description, paramY : window.selectedEquip1},
function(data) {
document.getElementById("equipmentRan").innerHTML = (data);
}
);
});
}

Categories