React how to test function called in FileReader onload function - javascript

I have the below code in a component. I want to test that onSubmit of the form, it calls the this.props.onUpload method in reader.
How can I test that?
My expect test is not working, I'm guessing it's because the this.props.onUpload is inside reader.onload function?
UploadForm.js
handleSubmit(e) {
e.preventDefault();
var inputData = '';
var file = this.state.file;
if (file) {
var reader = new FileReader();
reader.onload = (function(file) {
return function(e) {
inputData = e.target.result;
this.props.onUpload(inputData);
};
})(file).bind(this);
reader.readAsText(file);
}
}
render() {
return(
<form onSubmit={this.handleSubmit}>
<label> Enter File: <br/>
<input type="file" id="fileinput" onChange={this.handleChange}/>
</label>
<input type="submit" value="Submit" className="btn-upload" />
</form>
);
}
UploadForm.test.js
const mockOnUpload = jest.fn();
const file = new File([""], "filename");
const form = shallow(<UploadForm onUpload={mockOnUpload}/>);
const event = {
preventDefault: jest.fn(),
target: {files : [file]}
};
describe('when clicking `upload-file` button', () => {
beforeEach(() => {
form.find('#fileinput').simulate('change', event);
form.find('form').simulate('submit', event);
});
it('calls the handleSubmit CallBack', () => {
expect(mockOnUpload).toHaveBeenCalledWith(input);
});
});

Super great start with the mock upload being passed in as a prop and creating a fake event!
I always like running into testing issues like these in my own work because it tells me I have a code smell: if it's not easy to test, it likely means it is harder to predict, harder to debug, harder to explain, &c.
I recommend breaking out your functions to more singled responsibility. As it stands, your handleSubmit is doing a bit more than just handling submit. It also adds an onload function to an instance of FileReader and calls readAsText on that instance.
Your IIFE:
function(file) {
return function(e) {
inputData = e.target.result;
this.props.onUpload(inputData);
};
})(file).bind(this);
could be pulled out to an arrow function (taking care of bind) on the component:
readerOnLoad = file => (e) => {
this.props.onUpload(e.target.result);
}
(Also, is file needed as an argument here? Doesn't appear to be used.)
Then handleSubmit can interact withreaderOnLoad` like;
reader.onload = this.readOnLoad(file);
At this point, you can test that:
handleSubmit calls readerOnLoad with a file argument if it exists on state.
readerOnLoad, called with a file argument and then an event argument, calls this.props.onLoad with the event target result value.
If both of these tests pass, you can be confident that your code will work with real events, files, and FileReader instances.
It looks like you already understand how to pass in duck-type arguments (like events) that match native/browser objects, so just put those together and enjoy the peace of mind of your nicely collaborating functions!

Related

How to read file using FileReader.readAsText synchronously in JavaScript?

I am trying to read a CSV file using FileReader.readAsText() in JavaScript. But I am not able to get the value synchronously. I tried multiple approaches. But none is working. Below is the code I have so far:
1st Approach:
<input
id = "inputfile"
type = "file"
name = "inputfile"
onChange = {uploadFile} >
const uploadFile = (event: React.ChangeEvent < HTMLInputElement > ) => {
let resultSyncOutput = '';
connst files = event?.target.files;
if (files && files.length > 0) {
readAsTextCust(files[0]).then(resultStr => {
resultSyncOutput = resultStr;
});
}
// At this line I am not able to get the value of resultSyncOutput with the content of file sychronously
//Do something with the result of reading file.
someMethod(resultSyncOutput);
}
async function readAsTextCust(file) {
let resultStr = await new Promise((resolve) => {
let fileReader = new FileReader();
fileReader.onload = (e) => resolve(fileReader.result);
fileReader.readAsText(file);
});
console.log(resultStr);
return resultStr;
}
This is the first approach I tried ie, using async/await. I also tried to do it without aysnc/await and still was not able to succeed. It is critical for this operation to be synchronous. Also use of Ajax is not allowed in project.
NB: I checked a lot of answers in Stack Overflow and none provides a solution to this problem. So please do not mark this as duplicate. Answer to this particular question is not provided anywhere.
Please help me even if this looks simple to you
I found the solution resultSyncOutput = await readAsTextCust(files[0]); and declaring the calling function as async worked.
You need to set a callback function for the onload event callback to get the results. Also notice that you need to call readAsText on the uploaded CSV file.
You can use FileReader API inside input's onChange callback this way:
<input
id = "inputfile"
type = "file"
name = "inputfile"
onChange = function (event: React.ChangeEvent<HTMLInputElement>) {
const reader = new FileReader();
reader.onload = (e) => {
console.log(e.target?.result) // this is the result string.
};
reader.readAsText(event.target.files?.[0] as File);
};
No need for async/await as well.

Mock file upload to test a FileReader

Hello and thank you for your time reading this!
I am very interested to do unit tests while developing. I am new to tests in Javascript.
I have written a function to read files we choose,with an input, however I do not know how to test it.
I have read the documentation of Jasmine, about spies:
https://jasmine.github.io/api/2.6/global.html#spyOn
And:
https://jasmine.github.io/2.0/introduction.html
The code:
function readImage() {
if ( this.files && this.files[0] ) {
var FR= new FileReader();
var img = new Image();
FR.onload = function(e) {
img.src = e.target.result;
img.onload = function() {
ctx.drawImage(img, 0, 0, 512, 512);
};
};
FR.readAsDataURL( this.files[0] );
}
return [this.files, FR, img, ctx];
}
fileUpload.onchange = readImage;
The test I tried:
describe('readImage', function () {
it('should get at least one file ', function () {
spyOn(window, 'readImage');
fileUpload.dispatchEvent(new Event('onchange'));
expect(window.readImage).toHaveBeenCalled();
})
});
Also, fileUpload is:
function createUploadInput() {
body = document.getElementsByTagName("BODY")[0];
upload = document.createElement("input");
upload.setAttribute("type", "file");
upload.setAttribute("id", "fileUpload");
body.appendChild(upload);
return upload;
}
createUploadInput();
The output I get:
Expected spy readImage to have been called.
Error: Expected spy readImage to have been called.
at jasmine.Spec.<anonymous> (test/readImageSpec.js:42:34)
I think it is because of the readImage method has not been called in the test. The reason could be because fileUpload.dispatchEvent(new Event('onchange')); does nothing
Could you help me please?
I have also read:
How to trigger event in JavaScript?
Triggering event for unit testing
Using Jasmine to spy on a function without an object
Thank you for your help!
I have tried:
it('should get at least one file ', function () {
spyOn(window, 'readImage');
fileUpload.dispatchEvent(new Event('change'));
expect(window.readImage).toHaveBeenCalled();
})
But output is:
Expected spy readImage to have been called.
Error: Expected spy readImage to have been called.
at jasmine.Spec.<anonymous> (test/readImageSpec.js:42:34)
Also I tried:
it('should get at least one file ', function () {
spyOn(window, 'readImage');
fileUpload.onchange();
expect(window.readImage).toHaveBeenCalled();
})
And output:
Expected spy readImage to have been called.
Error: Expected spy readImage to have been called.
at jasmine.Spec.<anonymous> (test/readImageSpec.js:42:34)
I have also read: How can I trigger an onchange event manually?

Angular 2/4 FileReader Service

I was trying to create Angular 2/4 Service with possibily to upload files. I could not find solution on any resourse so I probably wanna ask you guys. So the idea is somewhere in Component there is input field with type=file. It has directive (change)="uploadFile($event)".
In component .ts file:
uploadFile(event) {
this.images.push(this.uploadImgService.uploadImage(event));
}
UploadImgService looks this way:
private img: string;
uploadImage(e) {
const file = e.target.files[0];
const pattern = /image-*/;
if (!file.type.match(pattern)) {
alert('You are trying to upload not Image. Please choose image.');
return;
}
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = () => {
this.img = reader.result;
};
return this.img;
}
So, I understand that operation is going async, but I can't figure out how to wrap it the way it could wait until img is load. I think it is the result of skill lack:(
When I post this code into component it surely works, but my idea is to make service.
Also, I'm just a beginner in Angular. So, if there is a better way to reilize this idea I would be glad to hear from you. Thanks!
You should return an observable like so:
uploadImage(e) {
const file = e.target.files[0];
const pattern = /image-*/;
if (!file.type.match(pattern)) {
alert('You are trying to upload not Image. Please choose image.');
return;
}
const reader = new FileReader();
reader.readAsDataURL(file);
return Observable.create(observer => {
reader.onloadend = () => {
observer.next(reader.result);
observer.complete();
};
});
}
And in the component, subscribe to the observable:
this.service.uploadImage(event).subscribe((img) => {
// Do what you want with the image here
});

How to get pasted value from Reactjs onPaste event

if i have an Reactjs input text element with onPaste event assigned to it, how could I get the pasted value in the response?
at the moment what i get in the console is a SyntheticClipboardEvent with all properties as null. I read that the console.log is a async checker so thats why the majority of values are null as they are looking ahead.
However I am wondering how to get the value.
Cheers
onPaste: function(e) {
console.log(e.clipboardData.getData('Text'));
},
https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/types
The formats are Unicode strings giving the type or format of the data,
generally given by a MIME type. Some values that are not MIME types
are special-cased for legacy reasons (for example "text").
example:
onPaste: function(e) {
console.log(e.clipboardData.getData('Text'));
console.log(e.clipboardData.getData('text/plain'));
console.log(e.clipboardData.getData('text/html'));
console.log(e.clipboardData.getData('text/rtf'));
console.log(e.clipboardData.getData('Url'));
console.log(e.clipboardData.getData('text/uri-list'));
console.log(e.clipboardData.getData('text/x-moz-url'));
}
Here is maybe a simpler "no paste" example using React hooks
export default function NoPasteExample() {
const classes = useStyles();
const [val, setVal] = React.useState("");
const [pasted, setPasted] = React.useState(false);
const handleChange = e => {
if (!pasted) {
setVal(e.target.value);
}
setPasted(false);
};
const handlePaste = () => {
setPasted(true);
};
return (
<form className={classes.root} noValidate autoComplete="off">
<div>
<TextField
value={val}
onPaste={handlePaste}
onChange={e => handleChange(e)}
/>
</div>
</form>
);
}
live demo: https://codesandbox.io/s/material-demo-w61eo?fontsize=14&hidenavigation=1&theme=dark
the data can be found on clipboardData, and parsed to string as follows:
event.clipboardData.items[0].getAsString(text=>{
// do something
})
For me this is quick and worked.
onPaste event fires before the input's value is changed.
So we need to use e.persist()
<input
onPaste={(e)=>{
e.persist();
setTimeout(()=>{ this.handleChange(e)},4)}
}
value={this.state.value}/>
first include Facebook DataTransfer module:
var DataTransfer = require('fbjs/lib/DataTransfer');
then you can do:
onPaste: function (evt) {
var data = new DataTransfer(evt.clipboardData);
var text = data.getText();
var html = data.getHTML();
var files = data.getFiles();
},
you welcome ;)

Javascript testing with mocha the html5 file api?

I have simple image uploader in a website and a javascript function which uses FileReader and converts image to base64 to display it for user without uploading it to actual server.
function generateThumb(file) {
var fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = function (e) {
// Converts the image to base64
file.dataUrl = e.target.result;
};
}
Now I am trying to write tests for this method using Mocha and Chai. My thinking is that I want to check if the file.dataUrl was successfully created and it is base64. So I would like to mock the local file somehow in testing environment (not sure how to do this). Or I should not test this at all and assume that this is working ?
The answer here depends a little. Does your "generateThumbs" method have other logic than loading a files contents and assign that to a property of a passed in object? Or does it have other logic such as generating the thumbnail from the image data, reading out file properties and assigning them to the file object? and so on?
If so then I would infact suggest you mock out the FileReader object with your own, so that you can control your test results. However, it isn't the FileReaders functionality you want to test, it is your own logic. So you should assume that FileReader works and test that your code that depends upon it works.
Now since the method you posted was a bit on the small side, In that case I would just assume it works, rename the method and work on testing the rest of your code. But there is a place for having such a mock, and I must admit it was quite fun to figure out how to mock the event target, so I will give an example here, using your method as a basis:
//This implements the EventTarget interface
//and let's us control when, where and what triggers events
//and what they return
//it takes in a spy and some fake return data
var FakeFileReader = function(spy, fakeData) {
this.listeners = {};
this.fakeData = fakeData;
this.spy = spy;
this.addEventListener('load', function () {
this.spy.loaded = true;
});
};
//Fake version of the method we depend upon
FakeFileReader.prototype.readAsDataURL = function(file){
this.spy.calledReadAsDataURL = true;
this.spy.file = file;
this.result = this.fakeData;
this.dispatchEvent({type:'load'}); //assume file is loaded, and send event
};
FakeFileReader.prototype.listeners = null;
FakeFileReader.prototype.addEventListener = function(type, callback) {
if(!(type in this.listeners)) {
this.listeners[type] = [];
}
this.listeners[type].push(callback);
};
FakeFileReader.prototype.removeEventListener = function(type, callback) {
if(!(type in this.listeners)) {
return;
}
var stack = this.listeners[type];
for(var i = 0, l = stack.length; i < l; i++) {
if(stack[i] === callback){
stack.splice(i, 1);
return this.removeEventListener(type, callback);
}
}
};
FakeFileReader.prototype.dispatchEvent = function(event) {
if(!(event.type in this.listeners)) {
return;
}
var stack = this.listeners[event.type];
event.target = this;
for(var i = 0, l = stack.length; i < l; i++) {
stack[i].call(this, event);
}
};
// Your method
function generateThumb(file, reader){
reader.readAsDataURL(file);
reader.addEventListener('load', function (e) {
file.dataUrl = base64(e.target.result);
});
}
Now we have a nice little object that behaves like a FileReader, but we control it's behavior, and we can now use our method and inject it into, thus enabling us to use this mock for testing and the real thing for production.
So we can now write nice unit tests to test this out:
I assume you have mocha and chai setup
describe('The generateThumb function', function () {
var file = { src: 'image.file'};
var readerSpy = {};
var testData = 'TESTDATA';
var reader = new FakeFileReader(readerSpy, testData);
it('should call the readAsDataURL function when given a file name and a FileReader', function () {
generateThumb(file, reader);
expect(readerSpy.calledReadAsDataURL).to.be.true;
expect(readerSpy.loaded).to.be.true;
});
it('should load the file and convert the data to base64', function () {
var expectedData = 'VEVTVERBVEE=';
generateThumb(file, reader);
expect(readerSpy.file.src).to.equal(file.src);
expect(readerSpy.file.dataUrl).to.equal(expectedData);
});
});
Here is a working JSFiddle example:
https://jsfiddle.net/workingClassHacker/jL4xpwwv/2/
The benefits here are you can create several versions of this mock:
what happens when correct data is given?
what happens when incorrect data is given?
what happens when callback is never called?
what happens when too large of a file is put in?
what happens when a certain mime type is put in?
You can offcourse massively simplify the mock if all you need is that one event:
function FakeFileReader(spy, testdata){
return {
readAsDataURL:function (file) {
spy.file = file;
spy.calledReadAsDataURL = true;
spy.loaded = true;
this.target = {result: testdata};
this.onload(this);
}
};
}
function generateThumb(file, reader){
reader.onload = function (e) {
file.dataUrl = base64(e.target.result);
};
reader.readAsDataURL(file);
}
Which is how I would actually do this. And create several of these for different purposes.
Simple version:
https://jsfiddle.net/workingClassHacker/7g44h9fj/3/

Categories

Resources