Home > OS >  Simulate file upload while testing Node Js application using Chai
Simulate file upload while testing Node Js application using Chai

Time:02-17

I am testing my API which receives a file as input. I tried using attach() function and it works pretty much fine. To cover all my use cases, I will have to use around 20 different input files. Instead of keeping all these 20 files, I was thinking of storing every such possible inputs in a single JSON file.

Example:

{
    "input-1":[
       "Name, Email, Phone, Address",
       "Sam, [email protected],0123498765,HomeAddress"
    ],
    "input-2":[
       "Name, Email, Phone, Address",
       "Yam, [email protected],0123498766,HomeAddress"
    ],
    "input-3":[
       "Name, Email, Phone, Address",
       "Ram, [email protected],0123498767,HomeAddress"
    ]
}

Here each entry (input-1,input-2,input-3) represents content for each file. This is just a sample. The actual file will have multiple lines for each such test input.

So, what I need is to extract each input and convert it as a file while calling the API. How do I achieve this using Chai?

CodePudding user response:

you could iterate data and and create tests and files dynamically, and attach them, including also all file related info for the server to parse:

const files = {
    "input-1": [
        "Name, Email, Phone, Address",
        "Sam, [email protected],0123498765,HomeAddress"
    ],
    "input-2": [
        "Name, Email, Phone, Address",
        "Yam, [email protected],0123498766,HomeAddress"
    ],
    "input-3": [
        "Name, Email, Phone, Address",
        "Ram, [email protected],0123498767,HomeAddress"
    ]
}

describe('uploading', () => {

    for (const [file, data] of Object.entries(files)) {

        it(`file ${file} should pass`, (done) => {

            chai.request(app)
                .post('/endpoint')
                // create file dynamically
                .attach('file', Buffer.from(data, 'utf-8'), {
                    // add file info accordingly
                    filename: `${file}.txt`,
                    contentType: 'text/plain',
                    knownLength: data.length
                })
                .end((err, res) => {
                    if (err) {
                        throw err;
                    }
                    expect(res).to.have.status(200);
                    done();
                })
        });
    }

});
  • Related