I'm a beginner in JavaScript and am creating my first project. I made a File Upload program which works, and I am now adding unit tests. I am trying to test how my program handles various different types of files (valid and invalid CSV/JSON files). However, my FileUploadHandler is expecting a File object and Mocha, which uses NodeJS, does not have a File class, so I cannot call new File to create File objects to pass in.
I tried to make a bunch of files manually and then pass them into the Mocha unit tests by path but I do not know how to get them to be passed in as File objects. -- I looked it up and it seems that you cannot access File objects by path via JS so if this is the case, what is a way I can do my unit testing?
I hope this was clear but if not, I can further clarify. Please help and thank you so much
** my function that I want to test takes in a File object
Ex.
describe('File testing', function() {
it('cannot process non csv/jsons', function() {
let f = new File([""], "html_file.html");
let tester = new FileUploadHandler(f);
## expecting error ##
})
})
In my implementation I use, mocha and chai to make expectations on desired inputs, here is an example of a failing test when user try to upload two files in one html form (this is not allowed by my multer rules, it is configured for single upload).
it('Check can not post more than 1 file', function(done) {
api.post('/files')
.set('Accept', 'application/json; charset=utf-8')
.field('Content-Type', 'multipart/form-data')
.field("sequence", 1)
.field("media", 10)
.attach("image", 'test/files/edit.png')
.attach("image", 'test/files/edit.png')
.expect(500)
.end(function(err, res) {
expect(res.status).to.equal(500);
done();
});
});
I just declared my form inputs, and a field type called image, that is the data holder for the image.
Related
The request.files method is great. I can map through multipart files and push them to s3 with the moveToDisk method. However, it seems that when moveToDisk returns an error or anything else it interrupts the loop. I'm pretty sure I have things at least close to set up correctly. I can successfully upload the first file and even store information to my database. But Anything beyond one file doesn't work. Anyone else having trouble with files or moveToDisk
const sprites = request.files("sprites");
for (let sprite of sprites) {
const collection = request.all().collection;
const uuid = uuidv4();
await client
.db("pixel-shop")
.collection("sprites")
.insertOne({
collection: collection,
token: sprite.fileName,
path: `pixel-shop/${collection}/${uuid}`,
created_at: new Date(),
});
await sprite?.moveToDisk(
`pixel-shop/sprites/${request.all().collection}`,
{ name: uuid }
);
}
Some things I've noticed in the logs are a cannot write file error which is weird because the first file writes fine, something about a .getUrl method, as well as some stuff about SSL but all my stuff aside from my localhost are secure.
my file structure is as follows:
file structure
I have two ejs views. I am taking a variable from index.ejs using document.querySelector. This variable is stored in index.js file.
I need to access this variable in board.js
How can I do so?
I have tried using:
module.exorts = varName and then require in board.js but it isn't working
index.js file
const btn = document.querySelector(".level1");
var levelMode;
btn.addEventListener("click", () => {
levelMode = btn.innerHTML;
alert(levelMode);
});
module.exports = levelMode;
board.js file
var levelMode = require("./index")
The console shows the following error:
uncaught reference: require is not defined
Im a new developer so take my advice with a grain of salt, but I feel I need to start by saying that js files dont "store" information that isn't the source code. Any information that you feel you need to pull from a variable is stored by the browser running the js file. If you need to pull data from the client my best advice is to first pass it to the server. You should get more familiar with the module you are using for HTTP Requests.
My question... how do I upload files using FilePond but onclick, not automatically like it does out of the box? Also, since I need to take a number of other actions with theses images (like display them for review prior to upload) and since I need to add other data to the FormData that gets sent (plus dispatch actions to Redux).
Normally I would create a FormObject append the files and other values to it before POSTing it to some endpoint (with any custom headers needed). However when I inspected the FilePond instance it seems like the only thing I have access to is a blob... not the actual files. Is this accurate? Do I need to follow some special FilePond specific technique to get file upload to work?
FilePond's docs have a custom config value called "server" that appears to have access to an actual file in the more advanced examples so is this the way it must be done? I can't just grab the files (from somewhere that I do not currently see on the FilePond instance) and append them to an object for use in my normal "service"?
Any tips are appreciated. In a React app I want to upload a variable number of files onclick after appending other form data and setting headers (using Axios, ideally) and POST these files to an API.
Example from their docs uses a prop like:
server="/api"
I want something like (fake code):
server={submitImages} <-- this should only happen onclick of some button
where:
submitImages = (fieldName, file) => {
const formData = new FormData()
formData.append(fieldName, file, file.name)
formData.append('foo', this.props.foo)
const docuploadresult = this.props.uploadDocs(formData) <-- a service that lives elsewhere and actually does the POST
docuploadresult.then(result => {
// success
}, error => {
// error
})
}
and my problems are that I don't see why this needs to happen in some special config object like server, don't see how to make this happen onclick, don't see an actual file anywhere.
I may be overthinking this?
FilePond offers the server property so it can handle the uploads for your. But this is not required, you can use getFiles to easily request all file items (and File objects) in FilePond and upload them yourself.
Add your own submit button to the form and use submitImages below to submit the files.
submitImages = (fieldName) => {
const formData = new FormData();
this.filepondRef.getFiles()
.map(fileItem => fileItem.file)
.forEach(file => {
formData.append(fieldName, file, file.name);
});
// upload here
}
If you want to show image previews you can add the image preview plugin.
https://pqina.nl/filepond/docs/patterns/plugins/image-preview/
In the VSTS Rest API, there's a piece of documentation showing me how to create a folder. Specifically, I would like to create a folder within the Shared Queries folder. It seems like I can do this with the REST API.
I would like to do the same thing with the VSTS Node API (vso-node-api). The closest analogous function I can seem to find would be WorkItemTrackingApi.createQuery. Is this the correct function to use?
When I try to use this function, I'm getting an error:
Failed request: (405)
That seems strange, since a "Method Not Allowed" error doesn't seem like the right error here. In other words, I'm not the person deciding what method (GET/POST/...etc) to use, I'm just calling the VSTS Node API's function which should be using the correct HTTP Request Method.
I think the error code would/should be different if something about my request is wrong (like providing bad parameters/data).
But, I would not be surprised if VSTS didn't like the data I provided with the request. I wrote the following test function:
async function createQueryFolder (QueryHeirarchyItem, projectId, query) {
let result = await (WorkItemTrackingApi.createQuery(QueryHeirarchyItem, projectId, query))
return result
}
I set some variables and called the function:
let projectID = properties.project // A previously set project ID that works in other API calls
let QueryHeirarchyItem = {
isFolder: true,
name: 'Test Shared Query Folder 1'
}
try {
let result = await createQueryFolder(QueryHeirarchyFunction, projectID, '')
Notice that I provided a blank string for the query - I have no idea what to provide there when all I want to create is a folder.
So, I think a lot of things could be wrong with my approach here, but also if my request parameters are wrong maybe I should be getting a 400 error? 405 leads me to believe that the VSTS Node API is making a REST call that the underlying VSTS REST API doesn't understand.
For the third parameter of the createQueryFolder, you should specify the folder path where you want to create the new folder.
Such as if you want to create a folder Test Shared Query Folder 1 under Shared Queries, you should specify parameters for createQueryFolder as:
let result = await createQueryFolder(QueryHeirarchyFunction, projectID, 'Shared Queries')
Due to some existing mongodb structure. I cant use Meteors Meteor.user. So when I try to insert new user calcMD5 says is not defined. How do I convert Md5 in meteor server? I dont know weather my approach is good or not. correct me if am wrong.
if (Meteor.isServer) {
newUser: function(email, password){
Users.insert({"emailid":email,"password":calcMD5(password)});
}
});
Here the template code
Template.signInWithEmail.events({
'click .btn-create-account': function(event, template) {
email = $('[name="emailAddress"]').val();
password = $('[name="password"]').val();
//Create new user
Meteor.call("newUser", email, password, function(error, result) {});
}
Problem is, the calcMD5 function does not exist in Meteor as it is. (nor JavaScript, nor NodeJS) I will assume you want to use this library or another one for your project.
If you want to be able to use an external library, you have to first add it into your Meteor project. You can do this by simply putting the javascript file in a folder such as server/lib/.
Or, if this gets too complicated, just add the crypto-md5 meteor package using:
meteor add jparker:crypto-md5
and call CryptoJS.MD5(password) instead of your calcMD5(password) function call.