当前位置: 首页 > 知识库问答 >
问题:

nodejs api路由测试(mocha)由于超时而失败

池麒
2023-03-14

我是nodejs测试的新手,使用mocha和Chai。现在,我在使用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实用程序,用于存储imagefile。我的测试代码是

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)

共有1个答案

国兴文
2023-03-14

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

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也需要在最高层添加,这样它才真正是异步

 类似资料:
  • 问题内容: 我是Mocha的新手,我正试图用它来测试一个简单的React组件。如果react组件没有任何CSS样式,则测试将通过,但是如果React组件内的标签包含任何className,则会引发语法错误: Testing.react.js testing.jsx 测试将通过: 在输入标签内添加className之后,出现错误: 测试结果: 我已经在网上搜索过,但到目前为止还没有运气。我想念什么吗

  • 英文原文:http://emberjs.com/guides/testing/testing-routes/ 单元测试方案和计算属性与之前单元测试基础中说明的相同,因为Ember.Route集成自Ember.Object。 路由测试可以通过集成测试或者单元测试来进行。集成测试对路由的测试具有更好地覆盖性,因为路由通常用来执行过渡和数据加载,这些测试在完整上下文中更加容易测试,而独立上下文则没有那么

  • 我正在用JUnit测试一个Spring Boot微服务,我对该服务的resources文件夹中的文件夹路径有问题。 为了通过测试,我必须把文件夹的绝对路径,相反,当使用完整的应用程序时,它与相对路径完美配合。我尝试了一些从相对到绝对路径的翻译,但都不起作用,测试只有在给出绝对路径时才通过,而不是计算。 这些是我的文件: JSONRequest。爪哇: DecryptServiceApplicati

  • 我试图解决hackerrank的一个问题,当我提交我的解决方案时,我得到一个错误,说明“由于超时而终止”。 请检查代码,并建议我如何优化。 语句:您有一个空序列,将向您提供查询。每个查询都是以下三种类型之一: 1 x-将元素x推入堆栈。2-删除堆栈顶部的元素。3-打印堆栈中的最大元素。 输入格式 输入的第一行包含一个整数。接下来的每一行都包含上述查询。(保证每个查询都是有效的。) 输出格式 对于每

  • 我在一个测试类中配置了一个简单的路由如下所示: 这是我执行上述代码时camel生成的跟踪片段: 我可以做什么来简单地下载文件?

  • 我创建了一个简单的quarkus(版本0.21.2)应用程序,它使用hibernate orm和panache将实体保存到h2数据库。该实体包括一个,共。我还做了一些测试来确保凝乳有效。这些测试都可以正常工作,但当我在本地运行它们时,我会遇到以下异常: 我的实体如下所示: 这是我的测试: 还有本地测试: 我不知道为什么它找不到。