如何在TestCafe中使用数据进行POST请求?

3

我是api测试的初学者,正在使用test-cafe,我已经编写了一个使用RequestHook进行GET请求的测试,它可以正常工作,我能够获取数据。但是当我尝试使用相同的RequestHook进行POST请求时,我无法发送数据,因为它需要是缓冲类型。

我无法将JSON数据转换为缓冲区类型。在进行POST请求时,我想知道是否这是使用RequestHook进行POST请求的正确方式,还是我们需要使用RequestLogger来进行POST请求?如果这两种方法都不正确,您能否指导我使用test-cafe进行api测试的任何教程!

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 */
});

预期结果是在POST请求成功后,状态码应该是200,但目前无法调用上述API端点,因为无法将JSON数据转换为缓冲区。

2个回答

4

RequestHook已被创建用于模拟或记录测试请求,但不是用来创建请求的。如果您需要发送请求并从服务器接收答案,可以使用标准的http模块或第三方axios库。


1
请求现在已经被npm弃用。 - anutter

1
我在进行API请求时使用ClientFunction。虽然不是理想的选择,但是我相信TestCafe在他们的待办事项中有一个"t.request"命令...
以下是使用ClientFunction发送API请求的示例,它使用了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;

我们称之为什么:

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 };
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接