由于超时,nodejs api路由测试mocha失败

如何解决由于超时,nodejs api路由测试mocha失败

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

exports.imageUpload = (req,res,next) => {
    Upload(req,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)

解决方法

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

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 秒,这是 mocha 文档中指定的默认超时时间 https://mochajs.org/#-timeout-ms-t-ms

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?