由于严格通过前端自动化工作流程的某些部分的复杂性,我们需要在前端自动化测试运行之前发出一个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();
});
});
我对JS不是很熟悉,所以可能做了一些明显的错误,只是不知道是什么。
TestCafe在Node.js环境下运行用户编写的测试代码。这意味着您可以在测试中编写任何自定义的JavaScript代码,并使用任何第三方库和模块进行请求。
RequestHooks机制旨在模拟或记录来自你的页面的请求,而不是发送请求。要从你的测试代码中发出HTTP请求,你可以使用标准的 https
nodejs模块。这里有一个例子。
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
});
另外,看看这些讨论类似问题的帖子。