【问题标题】:nodejs api route testing(mocha) failed due to timeoutnodejs api路由测试(mocha)由于超时而失败
【发布时间】:2021-03-30 15:22:55
【问题描述】:

我是使用 mocha 和 chai 进行 nodejs 测试的新手。现在我在使用 mocha 测试 API 路由处理程序时遇到问题。我的路由处理程序代码是

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"})
        }      
    })
}

Upload 函数只是一个用于存储图像文件的 multer 实用程序 我的测试代码是

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');
        })        
    })
})

运行此代码后显示的输出是

 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)

【问题讨论】:

  • 您确定您的上传在 2000 毫秒超时之前完成了吗?
  • 使用邮递员向该路由发送请求,仅需221.5ms POST /content/image_upload?file[] 200 221.563 ms - 765

标签: javascript node.js testing mocha.js chai


【解决方案1】:

我相信这个更新的代码应该可以工作

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 也需要在最顶层添加才能真正异步

【讨论】:

    【解决方案2】:

    我认为您的代码正在中断,因为上传时间超过 2 秒,这是 mocha 文档 https://mochajs.org/#-timeout-ms-t-ms 中指定的 mocha 的默认超时时间

    有两种方法可以解决这个问题:

    1. 在运行命令时添加全局级别超时以运行测试--timeout 5s
    2. 在测试用例本身中添加测试特定超时,例如
        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');
                })        
            })
        })
    

    只需检查上面代码 sn-p 中的第 3 行。更多细节在这里:https://mochajs.org/#test-level

    【讨论】:

    • neeraj,我确实尝试了 1 分钟超时仍然有同样的问题,我认为错误来自路由处理程序代码 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)
    • 您需要找出正确的超时时间。尝试使用--no-timeout 运行它以了解执行测试所需的时间。
    • 现在显示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)
    • @MurshidPc 您需要弄清楚为什么您的路由器代码不起作用并导致套接字挂起。只需查看其他相关问题,例如stackoverflow.com/questions/16995184/…
    猜你喜欢
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多