How to make post request with data in test-cafe?

老子叫甜甜 提交于 2020-06-15 06:44:24

问题


I am a beginner in api-testing, I'm using test-cafe and I have written test to make a GET request using RequestHook which is working fine, I was able to get the data but when I'm trying to make the POST request using the same RequestHook and I'm unable to send the data when making a request as it needs to be of type buffer.

I can't convert the data of type JSON to buffer. While making a POST request. I want to know whether this is the correct way to make a POST request using RequestHook or do we need to use the RequestLogger to make a POSTrequest? If both the methods are wrong can u guide me with any tutorials on api-testing using test-cafe!

class MyRequestHook extends RequestHook {
    constructor (requestFilterRules, responseEventConfigureOpts) {
        super(requestFilterRules, responseEventConfigureOpts);
        // ...
    }
   async onRequest (event) {
        const userData = {
            name: "Avinash",
            gender: "male",
            year : 1984,
            month: 12,
            day : 12,
            place : "Bengaluru, Karnataka, India"
        };
        const bufferedData = Buffer.from(JSON.stringify(userData));
        // the above code can't convert the data of type json to buffer type and the console stucks here, not able to print anything past this.
        event.requestOptions.body = bufferedData;
   }

   async onResponse (e) {
        console.log(e.body);
    }
}

const myRequestHook = new MyRequestHook(url: 'http://localhost:3000/user/details', {
    includeHeaders: true,
    includeBody: true
});

fixture `POST`
    .page('http://localhost:3000/user/details')
    .requestHooks(myRequestHook);

test('basic', async t => {
    /* some actions */
});

The expected result to be that it should give status 200 after the post request is successful, but at present, it is not able to call the above-mentioned api endpoint as it can't convert the JSON data to buffer.


回答1:


The RequestHook has been created to mock or log requests for testing but not to create requests. If you want to send a request and receive an answer from the server, use the request or request-promise module.    




回答2:


I use the ClientFunction when making API requests. It isn't ideal, and I believe TestCafe have a t.request command on their backlog...

Here's an example of using a ClientFunction to send an API request using fetch:

import { ClientFunction, t } from 'testcafe';

const fetchRequestClientFunction = ClientFunction((details, endpoint, method) => {
  return window
    .fetch(endpoint, {
      method,
      credentials: 'include',
      headers: new Headers({
        accept: 'application/json',
        'Content-Type': 'application/json',
      }),
      body: JSON.stringify(details),
    })
    .then(httpResponse => {
      if (httpResponse.ok) {
        return httpResponse.json();
      }
      return {
        err: true,
        errorMessage: 'There was an error trying to send the data',
      };
    });
});

const createFetchRequest = async (details, endpoint, method = 'POST') => {
  const apiResponse = await fetchRequestClientFunction(details, endpoint, method);
  await t.expect(apiResponse.err).eql(undefined, apiResponse.errorMessage);
  return apiResponse;
};

export default createFetchRequest;

And how we call it:

import createFetchRequest from '../custom_commands/createFetchRequest';
import linksAPI from '../helpers/linksAPI';

const userEndpoint = linksAPI.users;

export const createUserViaApi = async userDetails => {
  const apiResponse = await createFetchRequest(userDetails, userEndpoint);
  return { apiResponse };
};

export const updateUserViaApi = async userDetails => {
  const apiResponse = await createFetchRequest(userDetails, `${userEndpoint}/${userDetails.id}`, 'PUT');
  return { apiResponse };
};


来源:https://stackoverflow.com/questions/56427410/how-to-make-post-request-with-data-in-test-cafe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!