Reputation: 388
Due to complications with automating certain parts of our workflow strictly through the front-end, we need to make an HTTP request before our front-end automation tests run in order to setup test data.
Using the TestCafe docs I tried piecing something together, and while the test runs, the http request is not getting executed. Here's the code I have:
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();
});
});
I'm not super familiar with JS, so probably did something obviously wrong here, just not sure what it is.
Upvotes: 0
Views: 3712
Reputation: 6318
TestCafe runs test code written by the user in the Node.js environment. This means that you can write any custom JavaScript code in your tests and use any third-party library and module to make requests.
The RequestHooks mechanism is intended to mock or log requests from your page, not to send requests. To make an HTTP-request from your test code, you can use the standard https
nodejs module. Here’s an example:
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
});
Also, check out these threads where a similar inquiry was discussed:
How to make post request with data in test-cafe?
Upvotes: 5