How to send a form data in testcafe API request

81 Views Asked by At

I'm using testcafe API to make an API request. I need to use form data as the body of the post request. (The request looks something similar to curl -F username=xxx -F password=xxx https://xxxxx/api/login)

const response = await t.request.post({
      url: "https://xxxxx/api/login",
      body: {'username': 'xxx', 'password':'xxxx'},
      headers: { "content-type": "multipart/form-data" }
    });

    console.log(JSON.stringify(response));
}

This question may look similar to my requirement, but I don't need a 'Form' option. I just want to make a post request with form data.

1

There are 1 best solutions below

0
Bench Vue On

You need to use form-data library in your testCafe code.

testCafe code

test.js

import { Selector } from 'testcafe';
import FormData from 'form-data';
import fs from 'fs';

fixture`Test structure`
    .page`http://localhost:8080/login`;

test('Test1', async t => {
    // Create a form for 'multipart/form-data'
    const form = new FormData();
    form.append('username', 'admin');
    form.append('password', '123456');

    // Get the internal representation of the form-data to send as a buffer
    const buffer = await new Promise((resolve, reject) => {
        form.pipe(fs.createWriteStream('tempformdata'))
            .on('finish', function () {
                fs.readFile('tempformdata', (err, data) => {
                    if (err) reject(err);
                    resolve(data);
                });
            });
    });

    // Send the request with the correct headers and body
    const response = await t.request.post('http://localhost:8080/login', {
        headers: form.getHeaders(),
        body: buffer
    });

    console.log(JSON.stringify(response));
});

Server code

Demo local server.js by 'express'

const express = require('express');
const multer = require('multer');
const cors = require('cors');

const app = express();
app.use(cors())

// Add this line to handle 'application/x-www-form-urlencoded' content type
app.use(express.urlencoded({ extended: true }));

// for form-data
const forms = multer();
app.use(forms.array()); 

const postOptions = {
    origin: 'http://127.0.0.1:3000',
}

app.post('/login', cors(postOptions), (req, res) => {
    console.log(JSON.stringify(req.body, null, 4));

    // Extract username and password from request body
    const { username, password } = req.body;

    // Check if the username and password match the expected values
    if (username === 'admin' && password === '123456') {
        console.log('Login successful');
        res.status(200).send('Login successful');
    } else {
        console.log('Unauthorized: Incorrect username or password');
        // Send a 401 Unauthorized response if credentials don't match
        res.status(401).send('Unauthorized: Incorrect username or password');
    }
});

app.listen(8080, () => { console.log("Login Server on :8080") });

result

Left: server, Right: testCafe

enter image description here

Call by Postman

enter image description here