0

i am new to nodejs testing with mocha and chai.right now I am having issue while testing a API route handler with mocha. my route handler code is

exports.imageUpload = (req, res, next) => {
    Upload(req,res, async () => {     
        //get the image files and its original urls (form-data)
        let files = req.files['files[]'];
        const originalUrls = req.body.orgUrl;
        // check the input parameters
        if(files == undefined || originalUrls == undefined){
          res.status(400).send({status:'failed', message:"input field cannot be undefined"})
        }
        if(files.length > 0 && originalUrls.length > 0){
          //array of promises
          let promises = files.map(async(file,index)=>{
            //create a image document for each file 
            let imageDoc = new ImageModel({
              croppedImageUrl : file.path,
              originalImageUrl: (typeof originalUrls === 'string') ? originalUrls : originalUrls[index],
              status: 'New'
            });
            // return promises to the promises array
            return await imageDoc.save();
          });
          // resolve the promises
          try{
            const response = await Promise.all(promises);
            res.status(200).send({status: 'success', res:  response});           
          }catch(error){
            res.status(500).send({status:"failed", error: error})
          }
        }else{
          res.status(400).send({status:'failed', message:"input error"})
        }      
    })
}

the Upload function is just a multer utility to store the imagefile and my test code is

describe('POST /content/image_upload', () => {
    it('should return status 200', async() => {
        const response = await chai.request(app).post('/content/image_upload')
                .set('Content-Type', 'application/form-data')
                .attach('files[]',
                 fs.readFileSync(path.join(__dirname,'./asset/listEvent.png')), 'asset')
                .field('orgUrl', 'https://images.unsplash.com/photo-1556830805-7cec0906aee6?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1534&q=80')
        
        expect(response.error).to.be.false;
        expect(response.status).to.be.equal(200);
        expect(response.body.status).to.be.equal('success');
        response.body.res.forEach(item => {
            expect(item).to.have.property('croppedImageUrl');
            expect(item).to.have.property('originalImageUrl');
            expect(item).to.have.property('status');
            expect(item).to.have.property('_id');
        })        
    })
})

and the output shown after running this code is

 1) POST /content/image_upload
       should return status 200:
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/home/techv/content_capture/server/ContentServiceLib/api/test/image_upload.test.js)

2 Answers2

0

I believe this updated code should work

describe('POST /content/image_upload', async() => {
    await it('should return status 200', async() => {
        const response = await chai.request(app).post('/content/image_upload')
                .set('Content-Type', 'application/form-data')
                .attach('files[]',
                 fs.readFileSync(path.join(__dirname,'./asset/listEvent.png')), 'asset')
                .field('orgUrl', 'https://images.unsplash.com/photo-1556830805-7cec0906aee6?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1534&q=80')
        
        expect(response.error).to.be.false;
        expect(response.status).to.be.equal(200);
        expect(response.body.status).to.be.equal('success');
        response.body.res.forEach(item => {
            expect(item).to.have.property('croppedImageUrl');
            expect(item).to.have.property('originalImageUrl');
            expect(item).to.have.property('status');
            expect(item).to.have.property('_id');
        })        
    })
})

async needs to be added at the top most level as well for it to actually be asynchronous

Akshat
  • 46
  • 6
0

I think your code is breaking as the upload is taking more then 2 seconds which is the default timeout of mocha as specified in the mocha documentation at https://mochajs.org/#-timeout-ms-t-ms

There are two ways to overcome this problem:

  1. Add a global level timeout while running your command to run the tests --timeout 5s
  2. Add a test specific timeout in the test case itself e.g.
    describe('POST /content/image_upload', () => {
        it('should return status 200', async() => {
           this.timeout(5000) // Timeout
            const response = await chai.request(app).post('/content/image_upload')
                    .set('Content-Type', 'application/form-data')
                    .attach('files[]',
                     fs.readFileSync(path.join(__dirname,'./asset/listEvent.png')), 'asset')
                    .field('orgUrl', 'https://images.unsplash.com/photo-1556830805-7cec0906aee6?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1534&q=80')
            
            expect(response.error).to.be.false;
            expect(response.status).to.be.equal(200);
            expect(response.body.status).to.be.equal('success');
            response.body.res.forEach(item => {
                expect(item).to.have.property('croppedImageUrl');
                expect(item).to.have.property('originalImageUrl');
                expect(item).to.have.property('status');
                expect(item).to.have.property('_id');
            })        
        })
    })

Just check the line #3 in above code snippet. more details are here : https://mochajs.org/#test-level

neeraj jain
  • 224
  • 1
  • 8
  • neeraj, i did try 1 min timeout still having same issue, i think error is from route handler code `Error: Timeout of 60000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/home/techv/content_capture/server/ContentServiceLib/api/test/image_upload.test.js)` – Murshid Pc Mar 31 '21 at 06:12
  • you need to figure out the correct timeout.. try to run it with `--no-timeout` to know the time it takes for your test execution. – neeraj jain Mar 31 '21 at 06:26
  • now it showing `Error: socket hang up at createHangUpError (_http_client.js:323:15) at Socket.socketOnEnd (_http_client.js:426:23) at endReadableNT (_stream_readable.js:1145:12) at process._tickCallback (internal/process/next_tick.js:63:19)` – Murshid Pc Mar 31 '21 at 06:51
  • @MurshidPc you need to figure out why your router code is not working and causing socket hang up. just look up at other related questions like this one https://stackoverflow.com/questions/16995184/nodejs-what-does-socket-hang-up-actually-mean – neeraj jain Mar 31 '21 at 08:00