node.js - 如何在 test-cafe 中使用数据发出 post 请求?

标签 node.js post e2e-testing testcafe web-api-testing

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

我无法将 JSON 类型的数据转换为缓冲区。在制作 POST 时要求。 我想知道这是否是制作 POST 的正确方法使用RequestHook 请求还是我们需要使用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请求成功后应该给status 200,但目前无法调用上述api端点,因为它无法将JSON数据转换为buffer。

最佳答案

创建RequestHook 是为了模拟或记录测试请求,而不是创建请求。如果您需要发送请求并从服务器接收应答,您可以使用标准 http模块或第三方axios图书馆。

关于node.js - 如何在 test-cafe 中使用数据发出 post 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56427410/

相关文章:

java - Netbeans 的 RESTful Java 客户端 : javax. ws.rs.NotAcceptableException:HTTP 406 Not Acceptable

node.js - Cypress 间歇性无法验证基本 url 是否正在运行

docker - Gitlab CI : How to configure cypress e2e tests with multiple server instances?

node.js - 使用 Let's Encrypt SSL 证书在 ExpressJS Node 应用程序中握手失败

node.js - 更新插入不适用于 updateOnebulkWrite v3.4

javascript - 使用 Axios 发布数据

java - Reddit api Oauth : Server returned HTTP response code: 411 for URL error

regex - 如何将变量插入正则表达式 .match() 断言中?

javascript - 我可以在多个 HTML 页面中使用套接字吗?

node.js - 无法更新 npm(缺少访问权限)