繁体   English   中英

如何在testcafe中调用外部异步等待功能

[英]how to call external async await function in testcafe

我有具有功能的helper.js

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;

我想在执行测试后在testcafe脚本中使用此功能

在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)
});

如何解决这个问题?

我尝试使用clientFunction但由于_ref is not defined _ref而出错,代码如下

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

如果getLink方法必须读取DOM中的内容(超出Selector的范围)或必须在浏览器中计算某些特殊内容,则必须创建如下所示的clientFunction (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);
});

如果getLink方法不需要从DOM读取特殊内容,则无需创建clientFunction 您只需要创建一个辅助方法并将其导入(如@AlexSkorkin所建议):

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

注意,必须等待t.navigate()和mailer.getLink()。

由于async / await函数在clientFunction内不起作用作为一种解决方法,我将测试移至单独的文件中,并将getLink()函数移至测试之外

如果要一个接一个地运行这两个文件,请在package.json中将脚本添加为“ testcafe chrome file1.js && testcafe chrome file2.js”

任何直接的答案都欢迎

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM