Search code examples
javascriptnode.jsjestjsmultersupertest

How Can I test POST request with upload file?


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


Solution

  • 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("/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