questionar
questionar

Reputation: 284

how to call external async await function in testcafe

I have helper.js which has a function as

async function getLink() {
  try {
    const message = await authorize(content);
    const link = message.match(/href=\"(.*?)\"/i);
    return link[1];
  }
  catch(error) {
    console.log('Error loading:',+error);
    throw(error);
  }
}
module.exports.getLink = getLink;

I want to use this function inside the testcafe script after the test is executed

In test.spec.js

import { Selector } from 'testcafe';
let link = '';
fixture My fixture
.page `https://devexpress.github.io/testcafe/example/`;

 test('test1', async t => {

// do something with clientWidth
});
test('test2', async t => {
  // use the getLink function here from the helper.js to get the string value
  mailer.getLink().then(res=>{
    link = res;
  })
  t.navigateTo(link)
});

How to solve this issue?

I tried using clientFunction but getting error as _ref is not defined the code is as follows

const validationLink = ClientFunction(() => {
  return getLink();
}, { dependencies: { getLink } });
let link = await validationLink();

Upvotes: 2

Views: 2496

Answers (2)

hdorgeval
hdorgeval

Reputation: 3030

If the getLink method must read something in the DOM (that is outside the scope of the Selector) or must compute something special within the browser, you have to create a clientFunction like the following (with all code (no imported code) inside the clientFunction):

const getLink = ClientFunction((selector) => {
    return new Promise( (resolve) => {
        const element = selector();
        // check, in developper tools, what are the available properties in element
        console.log("element:", element);
        // code omitted for brevity that reads data from element and does special computation from it
        // build the result to be returned
        const result = 'the computed link';
        resolve(result);
    });
});

test('test2', async t => {
  const linkSelector = Selector('css selector');
  const link = await getLink(inputSelector);
  await t.navigateTo(link);
});

If the getLink method does not need to read something special from the DOM, then there is no need to create a clientFunction. You just need to create a helper method and import it (as suggested by @AlexSkorkin):

test('test2', async t => {
  const link = await mailer.getLink();
  await t.navigateTo(link)
});

Notice that t.navigate() must be awaited and mailer.getLink().

Upvotes: 5

questionar
questionar

Reputation: 284

Since async/await function won't work inside clientFunction As a workaround, I moved the test into a separate file and moved the getLink() function outside the test

if you want to run this two files one after other add the scripts in package.json as "testcafe chrome file1.js && testcafe chrome file2.js"

Any direct answers are welcomed

Upvotes: 0

Related Questions