I have a rest call within a clientscript, the result needs to be applied before the rest of the page js is executed.
How can i achieve this blocking await in a testcafe clientscript?
I get an error when using await as it may not be used at the top level. There seems to be no way to execute the rest call in testcafe and pass the result into the clientscript.
You can use a promise for this. Just cover every part of the code you want to promise. For example:
import { ClientFunction } from 'testcafe';
const clientFunction = ClientFunction(() => {
return Promise.resolve()
.then(() => fetch('https://api.kanye.rest/'))
.then((res) => res.json());
});
fixture`Fixture`;
test('Test', async (t) => {
const res = await clientFunction();
console.log(res);
await t.navigateTo('https://example.com/').debug();
})
Alternatively, wrap the call with 'await' with an async function.
//script.js
(async function() {
const resp = await fetch('https://api.kanye.rest/');
const data = await resp.json();
console.log(`${new Date().toISOString()} -> Client script executed`);
console.log(data);
})()
//test.js
fixture`Fixture`.clientScripts('./script.js').page('https://www.devexpress.com/');
test('Test', async (t) => {
console.log(`${new Date().toISOString()} -> Start test`);
await t.debug();
})