使用ES6在Javascript中返回异步数组的结果

时间:2018-12-11 15:46:41

标签: javascript node.js mocha chai

我是Java的新手,正在努力了解如何或至少如何最好地将数组值返回到另一个脚本以再次声明其值。

上下文是我想使用Puppeteer从WebElement属性中获取一些字符串值,然后使用Chai Expect库来声明正确的值(否则)。

到目前为止,我的代码是:

//app.spec.js
const clothingChoice = await frame.$eval('#option-clothing-5787', e => e.getAttribute('value'));
const groceryChoice = await frame.$eval('#option-clothing-4556', e => e.getAttribute('value'));
const wineChoice = await frame.$eval('#option-clothing-4433', e => e.getAttribute('value'));
const voucherChoice = await frame.$eval('#option-clothing-3454', e => e.getAttribute('value'));

function testFunction() {
  return new Promise(function(resolve, reject) {
    resolve([clothingChoice, groceryChoice, wineChoice, voucherChoice]);
  });
}

async function getChosenItemValues() {
  const [clothingChoice, groceryChoice, wineChoice, voucherChoice] = await testFunction();

  console.log(clothingChoice, groceryChoice, wineChoice, voucherChoice);

}

getChosenItemValues();

module.exports = getChosenItemValues;

};

我只需要了解如何导入当前仅打印为以下内容的值即可:

1|clothing|option 1|grocery|option 1|wine|option 1|voucher|option

...进入另一个文件test.js,我要在其中使用chai声明它们的存在,如下所示:

expect(clothingChoice).to.equal('1|clothing|option');

1 个答案:

答案 0 :(得分:0)

尝试一下:

// app.spec.js (.spec is normally reserved for test files, you may to change the name to avoid confusion)
const clothingChoice = frame.$eval('#option-clothing-5787', e => e.getAttribute('value'));
const groceryChoice = frame.$eval('#option-clothing-4556', e => e.getAttribute('value'));
const wineChoice = frame.$eval('#option-clothing-4433', e => e.getAttribute('value'));
const voucherChoice = frame.$eval('#option-clothing-3454', e => e.getAttribute('value'));

async function getChosenItemValues() { 
    return await Promise.all([clothingChoice, groceryChoice, wineChoice, voucherChoice]);
}

module.exports = {
    getChosenItemValues
};  

注意:frame.$eval肯定会返回Promise吗?我没有使用Puppeteer的经验。

// test file
const app = require('/path/to/app.spec.js');

describe('Suite', function() {
    it('Returns expected values', function(done) {
        app.getChosenItemValues()
            .then(res => {
                const [clothingChoice, groceryChoice, wineChoice, voucherChoice] = res;

                // assertions here

                done();
            });
    });
});

如果测试功能的格式不正确,请不要使用Mocha或Chai。