I've got some code running within a Vue.js component, but I get the following error:
TypeError: Cannot read property 'then' of undefined
I just want to run loadingAnimation() before the filereading, but searching on the internet for this error didn't really help me. What is the best way of doing this?
This is my code:
openFileBrowse() {
var vm = this;
var input = document.getElementById("filebutton");
if (input.files[0].type != "application/vnd.ms-excel"){
alert("You have uploaded a wrong file type. We require a .csv file not a " + input.files[0].type + " file.");
} else {
//Update loader text
vm.updateLoader('parsing csv');
//Start loadscreen
vm.loadingAnimation().then(function () {
//Start reading data
var reader = new FileReader();
var csvData = "";
var jsonData;
var iconv = require('iconv-lite');
reader.onload = function(){
csvData = iconv.decode(reader.result, 'latin1');
jsonData = vm.tsvJSON(csvData);
vm.addFiles(jsonData);
};
reader.onloadend = function(){
//Go to visualization page
router.push({ name: 'Visualization' });
};
reader.readAsText(input.files[0]);
});
}
},
loadingAnimation() {
//Make loading screen visible with animation
var target = document.getElementById('loadBox');
target.classList.remove('hidden')
setTimeout(function () {
target.classList.remove('visuallyhidden');
}, 20);
}
loadingAnimation isn't an async function and doesn't explicitly return a promise, so calling it doesn't give you a promise. In fact, it doesn't have any explicit return value, so calling it will always give you undefined.
If you want it to return a promise that will be fulfilled when the timer callback is fired, you have to code it. For instance:
loadingAnimation() {
return new Promise(resolve => {
//Make loading screen visible with animation
var target = document.getElementById('loadBox');
target.classList.remove('hidden')
setTimeout(function () {
target.classList.remove('visuallyhidden');
resolve();
}, 20);
});
}
Here how my code looks like:
var ws = null;
var _open = function(address) {
ws = new WebSocket(address);
ws.onopen = onOpen;
ws.onclose = onClose;
ws.onmessage = onMessage;
ws.onerror = onError;
};
var close = function() {
if (ws) ws.close();
};
var onOpen = function() {
// do something
};
var onClose = function() {
ws = null;
retry();
};
var onError = function(event) {
ws = null;
retry();
};
var onMessage = function(event) {
// do something
};
var retry = function() {
setTimeout(function() {
// extract what I need from location.href
var address = composeWsAddress(extractHostname(location.href));
_open(address);
}, 3000);
};
WebSocketClient = {
init: function() {
var address = composeWsAddress(extractHostname(location.href));
_open(address);
}
};
It should work in this way:
at start (init) it tries to connect
if fails (onError) it tries again after 3 s
if succeeds (onOpen) and then the connection closes (onClose) it tries again after 3 s
It works but on the WebSocket server I receive a number of new connections how many times they failed. For example, I launch my client application and after 30 s start the server. Now I have about 10 connections opened (one every 3 s).
Here I read I should not take care of "delete" each instance created by new WebSocket. Anyway I set it to null when the connection fails or closes.
So why it still keeps the old instances?
I followed this post
Having form using angular and firebase achievementsapp.firebaseapp.com, you can register and then if you click on the green plus it should pop the form, upload button is not working and when click on Add button it gives me this error Error: Firebase.set failed: First argument contains undefined in property 'achv_img'
controller code:
myApp.controller('MeetingsController',
function($scope, $rootScope, $firebase, Uploader,
CountMeetings, FIREBASE_URL) {
var ref = new Firebase(FIREBASE_URL + '/users/' +
$rootScope.currentUser.$id + '/meetings');
var meetingsInfo = $firebase(ref);
var meetingsObj = meetingsInfo.$asObject();
meetingsObj.$loaded().then(function(data) {
$scope.meetings = data;
}); //make sure meetings data is loaded
$scope.addMeeting = function() {
meetingsInfo.$push({
name: $scope.meetingname,
description: $scope.meetingdescription,
achv_type: $scope.achvtype,
achv_date: $scope.achvdate,
achv_img : $scope.achvimg,
date: Firebase.ServerValue.TIMESTAMP
}).then(function() {
$scope.meetingname='';
$scope.achvtype = '';
$scope.meetingdescription='';
$scope.achvdate='';
$scope.achvimg= $scope.meetingsInfoImgData;
});
Uploader.create($scope.meetingsInfo);
$scope.handleFileSelectAdd = function(evt) {
var f = evt.target.files[0];
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
var filePayload = e.target.result;
$scope.meetingsInfoImgData = e.target.result;
document.getElementById('pano').src = $scope.meetingsInfoImgData;
};
})(f);
reader.readAsDataURL(f);
};
document.getElementById('file-upload').addEventListener('change', $scope.handleFileSelectAdd, false);
}; //addmeeting
$scope.deleteMeeting = function(key) {
meetingsInfo.$remove(key);
}; //deleteMeeting
}); //MeetingsController
In reader.onload() you take the image data from the file and put it into $scope.meetingsInfoImgData:
reader.onload = (function(theFile) {
return function(e) {
var filePayload = e.target.result;
$scope.meetingsInfoImgData = e.target.result;
document.getElementById('pano').src = $scope.meetingsInfoImgData;
};
})(f);
My original answer then uses its equivalent of this $scope.meetingsInfoImgData later to populate the JavaScript object that it sends to Firebase:
$scope.episode.img1 = $scope.episodeImgData;
var episodes = $firebase(ref).$asArray();
episodes.$add($scope.episode);
Your code does nothing with $scope.meetingsInfoImgData when it tries to create the object in Firebase. You'll probably need something akin to $scope.episode.img1 = $scope.episodeImgData; in your code too.
If for some reason you can not fix it at the source, to make sure your object does not contain any undefined props use this simple trick:
JSON.parse( JSON.stringify(ObjectToSave ) )
For more info take a look at this codePen: http://codepen.io/ajmueller/pen/gLaBLX
I'm trying to use WebSocket for replacing Backbone.sync method.
Then I created three instance of "Sample" model named sample1, sample2 and sample3 and call fetch() method. Each request was successfully sent to the server.
However, when response data coming from the server, every response is set to the sample1. In other word, backbone.js triggered change event and only sample1 instance catch it.
I know there's good library named backbone.WS. However i would like to know why below code didn't work properly. Please give me any comments.
$(document).ready(function() {
var ws;
var url = ws://localhost:8080/application/sample;
Backbone.sync = function(method, model, options) {
var data = JSON.stringify({
'method' : method,
'data' : model.attributes}
);
if(ws == null) {
console.log("Create a new connection to the server.");
ws = new WebSocket(url);
console.log("Binding callback methods.");
ws.onopen = onOpen;
ws.onmessage = onMessage;
ws.onclose = onClose;
ws.onerror = onError;
}
function send(message) {
// Wait until the state of the socket is not ready and send the message when it is...
waitForSocketConnection(ws, function(){
console.log("message sent!!!");
ws.send(message);
});
}
// Make the function wait until the connection is made...
function waitForSocketConnection(socket, callback){
setTimeout(
function () {
if (socket.readyState === 1) {
console.log("Connection is made")
if(callback != null){
callback();
}
return;
} else {
console.log("Waiting for connecting...")
waitForSocketConnection(socket, callback);
}
}, 10); // wait 5 milisecond for the connection...
}
function onOpen(event) {
console.info("Connection established to " + url);
};
function onMessage(event) {
console.info("Message Received!");
var message = JSON.parse(event.data);
console.log("model: " + JSON.stringify(model.attributes));
model.set(message);
};
function onClose(event) {
console.log(event.code);
};
function onError() {
console.warn("There was an error with your websocket.");
}
send(data);
console.log("Request is sent to the server.");
options.success(message);
};
var Sample = Backbone.Model.extend({
defaults : {
id : 0,
name : "default"
}
});
var sample1 = new Sample({id:1});
var sample2 = new Sample({id:2});
var sample3 = new Sample({id:3});
sample1.fetch();
sample2.fetch();
sample3.fetch();
sample1.on("change", function(model) {
console.log("--- onChange method in sample 1");
});
sample2.on("change", function(model) {
console.log("+++ onChange method in sample 2");
});
sample3.on("change", function(model) {
console.log("=== onChange method in sample 3");
});
}
I'm trying to make this test work, but I couldn't get my head around how to write a test with FileReader. This is my code
function Uploader(file) {
this.file = file;
}
Uploader.prototype = (function() {
function upload_file(file, file_contents) {
var file_data = new FormData()
file_data.append('filename', file.name)
file_data.append('mimetype', file.type)
file_data.append('data', file_contents)
file_data.append('size', file.size)
$.ajax({
url: "/upload/file",
type: "POST",
data: file_contents,
contentType: file.type,
success: function(){
// $("#thumbnail").attr("src", "/upload/thumbnail");
},
error: function(){
alert("Failed");
},
xhr: function() {
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',showProgress, false);
} else {
console.log("Upload progress is not supported.");
}
return myXhr;
}
});
}
return {
upload : function() {
var self = this,
reader = new FileReader(),
file_content = {};
reader.onload = function(e) {
file_content = e.target.result.split(',')[1];
upload_file(self.file, file_content);
}
}
};
})();
And this is my test
describe("Uploader", function() {
it("should upload a file successfully", function() {
spyOn($, "ajax");
var fakeFile = {};
var uploader = new Uploader(fakeFile);
uploader.upload();
expect($.ajax.mostRecentCall.args[0]["url"]).toEqual("/upload/file");
})
});
But it never gets to reader.onload.
The problem here is the use of reader.onload which is hard to test. You could use reader.addEventListener instead so you can spy on the global FileReader object and return a mock:
eventListener = jasmine.createSpy();
spyOn(window, "FileReader").andReturn({
addEventListener: eventListener
})
then you can fire the onload callback by yourself:
expect(eventListener.mostRecentCall.args[0]).toEqual('load');
eventListener.mostRecentCall.args[1]({
target:{
result:'the result you wanna test'
}
})
This syntax changed in 2.0. Code below gives an example based on Andreas Köberle's answer but using the new syntax
// create a mock object, its a function with some inspection methods attached
var eventListener = jasmine.createSpy();
// this is going to be returned when FileReader is instantiated
var dummyFileReader = { addEventListener: eventListener };
// pipe the dummy FileReader to the application when FileReader is called on window
// this works because window.FileReader() is equivalent to new FileReader()
spyOn(window, "FileReader").and.returnValue(dummyFileReader)
// your application will do something like this ..
var reader = new FileReader();
// .. and attach the onload event handler
reader.addEventListener('load', function(e) {
// obviously this wouldnt be in your app - but it demonstrates that this is the
// function called by the last line - onloadHandler(event);
expect(e.target.result).toEqual('url');
// jasmine async callback
done();
});
// if addEventListener was called on the spy then mostRecent() will be an object.
// if not it will be null so careful with that. the args array contains the
// arguments that addEventListener was called with. in our case arg[0] is the event name ..
expect(eventListener.calls.mostRecent().args[0]).toEqual('load');
// .. and arg[1] is the event handler function
var onloadHandler = eventListener.calls.mostRecent().args[1];
// which means we can make a dummy event object ..
var event = { target : { result : 'url' } };
// .. and call the applications event handler with our test data as if the user had
// chosen a file via the picker
onloadHandler(event);
I also faced similar problem and was able to achieve it without use of addeventlistener. I had used onloadend, so below is what I did.
My ts file had below code:-
let reader = new FileReader();
reader.onloadend = function() {
let dataUrl = reader.result;
// Some working here
};
reader.readAsDataURL(blob);
My spec file (test) case code :-
let mockFileReader = {
result:'',
readAsDataURL:(blobInput)=> {
console.log('readAsDataURL');
},
onloadend:()=> {
console.log('onloadend');
}
};
spyOn<any>(window, 'FileReader').and.returnValue(mockFileReader);
spyOn<any>(mockFileReader, 'readAsDataURL').and.callFake((blobInput)=> {
// debug your running application and assign to "encodedString" whatever
//value comes actually after using readAsDataURL for e.g.
//"data:*/*;base64,XoteIKsldk......"
mockFileReader.result = encodedString;
mockFileReader.onloadend();
});
This way you have mocked the FileReader object and returned a fake call to your own "readAsDataURL". And thus now when your actual code calls "reasAsDataURL" your fake function is called in which you are assigning an encoded string in "result" and calling "onloadend" function which you had already assigned a functionality in your code (.ts) file. And hence it gets called with expected result.
Hope it helps.
I think the best way is to use the real FileReader (don't mock it), and pass in a real File or Blob. This improves your test coverage and makes your tests less brittle.
If your tests don't run in IE, you can use the File constructor, e.g.
const fakeFile = new File(["some contents"], "file.txt", {type: "text/plain"});
If you need to be compatible with IE, you can construct a Blob and make it look like a file:
const fakeFile = new Blob(["some contents"]);
fakeFile.name = "file.txt";
fakeFile.type = "text/plain";
The FileReader can read either of these objects so there is no need to mock it.
i found easiest for myself to do next.
mock blob file
run reader.onload while in test environment.
as result - i do not mock Filereader
// CONTROLLER
$scope.handleFile = function (e) {
var f = e[0];
$scope.myFile = {
name: "",
size: "",
base64: ""
};
var reader = new FileReader();
reader.onload = function (e) {
try {
var buffer = e.target.result;
$scope.myFile = {
name: f.name,
size: f.size,
base64: XLSX.arrayBufferToBase64(buffer)
};
$scope.$apply();
} catch (error) {
$scope.error = "ERROR!";
$scope.$apply();
}
};
reader.readAsArrayBuffer(f);
//run in test env
if ( typeof jasmine == 'object') {reader.onload(e)}
}
//JASMINE TEST
it('handleFile 0', function () {
var fileContentsEncodedInHex = ["\x45\x6e\x63\x6f\x64\x65\x49\x6e\x48\x65\x78\x42\x65\x63\x61\x75\x73\x65\x42\x69\x6e\x61\x72\x79\x46\x69\x6c\x65\x73\x43\x6f\x6e\x74\x61\x69\x6e\x55\x6e\x70\x72\x69\x6e\x74\x61\x62\x6c\x65\x43\x68\x61\x72\x61\x63\x74\x65\x72\x73"];
var blob = new Blob(fileContentsEncodedInHex);
blob.type = 'application/zip';
blob.name = 'name';
blob.size = 11111;
var e = {0: blob, target: {result: {}}};
$scope.handleFile(e);
expect($scope.error ).toEqual("");
});
I struggled to figure out how to test onloadend when it gets called from readAsDataURL.
Here is a dump of what I ended up with.
Production code:
loadFileDataIntoChargeback(tempFileList) {
var fileNamesAndData = [];
for (var i = 0, f; f = tempFileList[i]; i++) {
let theFile = tempFileList[i];
var reader = new FileReader();
reader.onloadend = ((theFile) => {
return (fileData) => {
var insertionIndex = this.chargeback.fileList.length;
this.chargeback.fileList.push({ FileName: theFile.name, Data: fileData.target.result, FileType: theFile.type });
this.loadFilePreviews(theFile, insertionIndex);
}
})(f);
reader.readAsDataURL(f);
}
this.fileInputPath = "";
}
Test code:
describe('when the files are loaded into the chargeback', () => {
it('loads file previews', () => {
let mockFileReader = {
target: { result: '' },
readAsDataURL: (blobInput) => {},
onloadend: () => {}
};
spyOn(chargeback, "loadFilePreviews");
spyOn(window, 'FileReader').and.returnValue(mockFileReader);
spyOn(mockFileReader, 'readAsDataURL').and.callFake((blobInput) => {
mockFileReader.onloadend({ target: { result: "data:image/jpeg;base64,/9j/4QAYRXh" } });
});
var readFileList = chargeback.getArrayFromFileInput([getImageFile1()]);
chargeback.loadFileDataIntoChargeback(readFileList);
expect(chargeback.loadFilePreviews).toHaveBeenCalled();
});
});