首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在testcafe中调用外部异步等待函数

如何在testcafe中调用外部异步等待函数
EN

Stack Overflow用户
提问于 2018-12-19 20:59:11
回答 2查看 1.8K关注 0票数 2

我有一个helper.js,它的函数是

代码语言:javascript
复制
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中

代码语言:javascript
复制
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出现错误,代码如下

代码语言:javascript
复制
const validationLink = ClientFunction(() => {
  return getLink();
}, { dependencies: { getLink } });
let link = await validationLink();
EN

回答 2

Stack Overflow用户

发布于 2018-12-20 06:05:19

如果getLink方法必须读取DOM中的内容(即在Selector的作用域之外)或必须在浏览器中计算特殊内容,则必须创建如下所示的clientFunction (在clientFunction中包含所有代码(不导入代码)):

代码语言:javascript
复制
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。您只需要创建一个helper方法并导入它(由@AlexSkorkin建议):

代码语言:javascript
复制
test('test2', async t => {
  const link = await mailer.getLink();
  await t.navigateTo(link)
});

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

票数 5
EN

Stack Overflow用户

发布于 2018-12-20 02:24:30

由于异步/等待函数不能在clientFunction内部作为解决办法,因此我将测试移到了一个单独的文件中,并将getLink()函数移到了测试之外

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

欢迎任何直接的回答

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53851782

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档