簡體   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