javascript - 如何在testcafe中调用外部异步await函数

标签 javascript automated-tests e2e-testing web-testing 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 未定义代码如下

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()。

关于javascript - 如何在testcafe中调用外部异步await函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53851782/

相关文章:

ios - MonkeyTalk 错误报告到 .txt/excel 文件

javascript - 识别切换栏元素文本并在 Protractor 中单击它

javascript - 获取跨源请求的响应自定义 header

javascript - 使用箭头键导航表单域和编辑文本

xcode - 我可以多次运行 XCTest 套件吗?

testing - 用小团队(和很少的时间)对大型项目进行手动与自动测试

javascript - Testcafe 客户端功能失败 "An error occurred in ClientFunction code: ReferenceError: _from2 is not defined"

testing - 选择器应该用一个函数初始化

javascript - 如果已经使用 angularjs 登录,如何避免显示登录页面?

javascript - 判断图片宽高比是否合适