'result' in FileReader has [object Object] instead of string after using upload method and reading file content
marekdano opened this issue ยท 4 comments
Current behavior:
Desired behavior:
Thanks for creating this library. I like how clear is to use it to test upload file functionality.
I took the library to test uploading a JSON file, read the content in the file, set the state and display file content on the layout. I found while using this library, a JSON file uploads, FileReader executes, but the result returns [objectObject] instead of an expected string.
When I upload a file in the real app the FileReader result correctly contains a string which is a content of the uploaded file.
I'm not sure if there is a bug in the library or I missed something in my implementation which can be seen below.
Steps to reproduce: (app code and test code)
Please find the code that I use:
// implementation of file input
<input type="file" className="file-input" name="file" accept=".json" onChange={handleUploadFile}/>
// implementation of handleUploadFile
const handleUploadFile = (e: ChangeEvent<HTMLInputElement>) => {
const file = e && ((e.target as HTMLInputElement).files as FileList)[0];
if (file) {
const fileReader = new FileReader();
fileReader.onloadend = (e) => {
const content = fileReader.result as string;
console.log(content) // displays [object Object] instead of string
setInput(JSON.parse(content));
handleJSONChange(JSON.parse(content), null, 'input');
}
fileReader.readAsText(file);
}
}
// test
it.only('should upload a file', () => {
const fileName = 'upload-file.json';
const output = '{"sample": "json"}';
cy.fixture(fileName)
.then(fileContent => {
cy.get('.file-input').upload({fileContent, fileName, mimeType: 'application/json'}, { subjectType: 'input', force: true })
})
.should(() => {
cy.get('#input > .jsoneditor > .jsoneditor-outer > .ace_editor > textarea')
.should(($div) => {
const values = $div.map((i, el) => Cypress.$(el).text())
const result = values
.get()
.map(line => line.trimLeft())
.join('')
expect(result).to.eq(JSON.stringify(output))
});
});
});
Versions
Just ran into this myself. The problem is that cy.fixture
detects that the file is JSON and loads as such. This fixed the problem for me:
cy.fixture(fileName).then(fileJson => {
const fileContent = JSON.stringify(fileJson)
cy.get('input[type="file"]').upload({ fileContent, fileName, mimeType: 'application/json' })
})
Thank you, @justinlittman! You'll fix it for me!
I'm closing the issue.
Hi @marekdano!
Thanks for submitting the issue. I am really happy small community around the plugin now helps each other resolving such tricks.
This thing may be not obvious for other users as well so I intend to put this to README.md#Caveats section.
And shout out to @justinlittman for quick help!
@all-contributors add @justinlittman for question.
I've put up a pull request to add @justinlittman! ๐