如何测试具有上传文件功能的POST请求?

huangapple go评论96阅读模式
英文:

How Can I test POST request with upload file?

问题

I can provide a translation of your code. It seems you want a translation of the code comments and some code portions. Here's the translation:

我有一个简单的Node.js项目使用Handlebars我开始使用Jest和SuperTest进行测试但我不知道如何测试带有请求主体和文件数据的POST请求

```javascript
app.post('/new-team', upload.single('shield'), (req, res) => {
  const teams = JSON.parse(fs.readFileSync('./data/teams.db.json'));
  const {
    name, tla, country, address, website, founded,
  } = req.body;
  const state = teams.find((team) => team.tla === tla.toUpperCase());
  if (state) {
    res.render('new-team', {
      layout: 'main',
      data: {
        error: 'Ops! 你想创建的球队已经存在TLA,请再试一次',
      },
    });
  } else {
    const newTeam = {
      area: {
        name: country,
      },
      name,
      tla: tla.toUpperCase(),
      country,
      **crestUrl: `/shields/${req.file.filename}`, //这里是我的问题**
      address,
      website,
      founded,
    };
    teams.push(newTeam);
    fs.writeFile('./data/teams.db.json', JSON.stringify(teams), (err) => {
      res.status(200).json({
        status: '成功',
        data: {
          teams,
        },
      });
    });
    res.redirect('/team-created');
  }
  res.render('new-team', {
    layout: 'main',
  });
});

我尝试使用以下代码发送主体:

test('POST /new-team', async () => {
  const newTeam = {
    name: 'rosario central',
    tla: 'CARC',
    country: 'Argentina',
    address: 'colombress 1245',
    website: 'www.central.com',
    founded: '1886',
  };
  const response = await request(baseURL).post('/new-team').send(newTeam);
  expect(response.status).toBe(200);
});

但是我不知道如何发送数据以获取req.file.filename,因为我无法访问req.file.filename。


I've translated the code comments and some code portions as you requested. If you have any specific questions or need further assistance, please feel free to ask.

<details>
<summary>英文:</summary>

I have a simple node.js with handlebars proyect and I started to do Tests with jest and superTest and I dont know how can I test this POST request with body and file data:


app.post('/new-team', upload.single('shield'), (req, res) => {
const teams = JSON.parse(fs.readFileSync('./data/teams.db.json'));
const {
name, tla, country, address, website, founded,
} = req.body;
const state = teams.find((team) => team.tla === tla.toUpperCase());
if (state) {
res.render('new-team', {
layout: 'main',
data: {
error: 'Ops! The team you want to create has an existing TLA, try it again',
},
});
} else {
const newTeam = {
area: {
name: country,
},
name,
tla: tla.toUpperCase(),
country,
crestUrl: /shields/${req.file.filename}, //HERE IS MY PROBLEM
address,
website,
founded,
};
teams.push(newTeam);
fs.writeFile('./data/teams.db.json', JSON.stringify(teams), (err) => {
res.status(200).json({
status: 'success',
data: {
teams,
},
});
});
res.redirect('/team-created');
}
res.render('new-team', {
layout: 'main',
});
});



I made this to try to send the body:

test('POST /new-team', async () => {
const newTeam = {
name: 'rosario central',
tla: 'CARC',
country: 'Argentina',
address: 'colombress 1245',
website: 'www.central.com',
founded: '1886',
};
const response = await request(baseURL).post('/new-team').send(newTeam);
expect(response.status).toBe(200);
});


but I dont know how to send the data to have **req.file.filename**

because, I cant access to req.file.filename

</details>


# 答案1
**得分**: 0

Your Express endpoint expects a `multipart/form-data` request body. To create one of these with SuperTest / SuperAgent, you can use the `.field()` and `.attach()` methods.

```lang-js
const response = await request(baseURL)
  .post("/new-team")
  .field("name", "roasario central")
  .field("tla", "CARC")
  // ... and other fields
  .attach("shield", "fixtures/shield.ext") // attach your file

See also the SuperAgent documentation for Multipart requests

英文:

Your Express endpoint expects a multipart/form-data request body. To create one of these with SuperTest / SuperAgent, you can use the .field() and .attach() methods

const response = await request(baseURL)
  .post(&quot;/new-team&quot;)
  .field(&quot;name&quot;, &quot;roasario central&quot;)
  .field(&quot;tla&quot;, &quot;CARC&quot;)
  // ... and other fields
  .attach(&quot;shield&quot;, &quot;fixtures/shield.ext&quot;) // attach your file

See also the SuperAgent documentation for Multipart requests

huangapple
  • 本文由 发表于 2023年4月11日 10:58:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75982096.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定