使用 TestCafe 发出真实的 HTTP 请求

anu*_*ter 0 javascript testing automated-tests e2e-testing testcafe

由于严格通过前端自动化我们工作流程的某些部分的复杂性,我们需要在前端自动化测试运行之前发出 HTTP 请求以设置测试数据。

使用 TestCafe 文档,我尝试将一些东西拼凑在一起,当测试运行时,http 请求没有得到执行。这是我的代码:

import {Selector, ClientFunction, RequestHook, RequestLogger} from 'testcafe';
import https from 'https';


fixture `Call Create Test Move`
    .before(async ctx => {
        test('test', async t => {
            const executeRequest = () => {
                return new Promise(resolve => {
                    const options = {
                        method: 'POST',
                        uri: 'https://api.com/move/sample',
                        headers: {
                            "X-Company-Secret": "xxxxxxx",
                            "X-Permanent-Access-Token": "xxxxxxx"
                        },
                        body: {
                            companyKey: 'xxxxxx'
                        },
                        json: true
                    };

                    const req = https.request(options, res => {
                        console.log('statusCode:', res.statusCode);
                        console.log('headers:', res.headers);
                        resolve();
                    });

                    req.on('error', e => {
                        console.error(e);
                    });

                    req.end();
                });
            };

            await executeRequest();
        });
    });
Run Code Online (Sandbox Code Playgroud)

我对 JS 不是很熟悉,所以可能在这里做了一些明显错误的事情,只是不确定它是什么。

Ale*_*aev 5

TestCafe 运行用户在 Node.js 环境中编写的测试代码。这意味着您可以在测试中编写任何自定义 JavaScript 代码,并使用任何第三方库和模块发出请求。

RequestHooks 机制旨在模拟或记录来自您页面的请求,而不是发送请求。要从您的测试代码发出 HTTP 请求,您可以使用标准的httpsnodejs 模块。下面是一个例子:

import https from 'https';

const executeRequest = () => {
    return new Promise(resolve => {
        const options = {
            hostname: ' https://api.com/move/sample',
            port:     443,
            path:     '/',
            method:   'POST'
        };

        const req = https.request(options, res => {
            console.log('statusCode:', res.statusCode);
            console.log('headers:', res.headers);
            resolve();
        });

        req.on('error', e => {
            console.error(e);
        });

        req.end();
    });
};

fixture `fixture`
    .page `http://google.com`
    .beforeEach(async t => {
        await executeRequest();
    });

test('test', async t => {
    // test code
});
Run Code Online (Sandbox Code Playgroud)

另外,请查看讨论类似查询的这些线程:

如何使用 test-cafe 中的数据进行发布请求?

发出外部请求