E
E
Emptyform2016-09-16 11:15:46
JavaScript
Emptyform, 2016-09-16 11:15:46

How to test file upload to server?

Hey!
I am writing a test to upload a file to the server. Here is the code:

describe('POST request', () => {
        describe('post file.ext', () => {
            it('returns 200 & the file', done => {
                let content = fs.readFileSync(`${fixtures}/small.png`, {encoding: 'utf-8'});

                var formData = {
                    /*attachments: [
                        fs.createReadStream(`${fixtures}/small.png`)
                    ],
                    */
                    /*my_file: fs.createReadStream(`${fixtures}/small.png`),
                    */
                    custom_file: {
                        value:  fs.createReadStream(`${fixtures}/small.png`),
                        options: {
                            filename: 'small.png',
                            contentType: mime.lookup(`${fixtures}/small.png`)
                        }
                    }
                };
                request.post({url: `${url}/small.png`, formData: formData}, (error, response, body) => {
                    if (error) return done(error);
                    expect(response.statusCode).to.equal(200);

                    var data = fs.readFileSync(`${filesDirectory}/small.png`, {encoding: 'utf-8'});
                    if (!data) return done(error);

                    expect(data).to.deep.equal(content);
                    done();
                });
            });
        });
    });

The test fails - the uploaded file does not match the original.
Garbage of the type is added to the beginning of the received file:
----------------------------628275255943632608493620
Content-Disposition: form-data; name="custom_file"; filename="small.png"
Content-Type: image/png

How can I make sure that the file does not change when uploaded to the server?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2016-09-16
@Emptyform

This is not garbage, it is part of the http protocol,
as a result, your file is loaded incorrectly if the subheadings end up in the
UPD file:

request.post({
  url: `${url}/small.png`,
  body: fs.createReadStream(`${fixtures}/small.png`),
  headers: {
    'Content-type': mime.lookup(`${fixtures}/small.png`),
    'x-filename': 'small.png'
  }
}, (error, response, body) => { /* Ваш код */ });
more or less like this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question