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

使用ES6返回Javascript中异步数组的结果,javascript,node.js,mocha.js,chai,Javascript,Node.js,Mocha.js,Chai,我是Javascript的新手,正在努力理解如何或至少如何最好地将数组值返回到另一个脚本以重新声明它们的值 上下文是我想使用Puppeter从WebElement属性获取一些字符串值,然后使用Chai expect库断言正确的值(或其他) 到目前为止,我的守则是: //app.spec.js const clothingChoice=等待帧。$eval('option-clothing-5787',e=>e.getAttribute('value'); const groceryChoice=

我是Javascript的新手,正在努力理解如何或至少如何最好地将数组值返回到另一个脚本以重新声明它们的值

上下文是我想使用Puppeter从WebElement属性获取一些字符串值,然后使用Chai expect库断言正确的值(或其他)

到目前为止,我的守则是:

//app.spec.js
const clothingChoice=等待帧。$eval('option-clothing-5787',e=>e.getAttribute('value');
const groceryChoice=wait frame.$eval('#option-things-4556',e=>e.getAttribute('value');
const wineChoice=wait frame.$eval('#option-things-4433',e=>e.getAttribute('value');
const voucherChoice=wait frame.$eval('#option-things-3454',e=>e.getAttribute('value');
函数testFunction(){
返回新承诺(功能(解决、拒绝){
解决([服装选择、杂货店选择、葡萄酒选择、凭证选择]);
});
}
异步函数getChosenItemValues(){
const[clothingChoice、groceryChoice、wineChoice、voucherChoice]=等待测试函数();
console.log(clothingChoice、groceryChoice、wineChoice、voucherChoice);
}
getChosenItemValues();
module.exports=getChosenItemValues;
};请尝试以下操作:

// 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
?我对木偶演员没有任何经验

// 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。

您的
testChoices
模块中有两层函数。从我所看到的情况来看,您没有调用导出模块中的匿名函数
choiceValue
。另外,您在
choiceValue
中返回的是一个对象,而不是一个数组。末尾还有一个冒号代替分号。为什么要从测试中导出某些内容?这与
index.js
文件有什么相似之处?这不是一个测试文件吗?“你到底在输出什么?”DaveNewton简单的答案是——我不知道。在Node/JS上似乎没有什么共识,在本例中,我完全错了。我试图找到一些文件结构的约定,例如,但是…谢谢@gnusey,但是当我尝试运行测试时,值,例如choiceValue.clothingChoice仍然显示为“未定义”:AssertionError:expected undefined等于“1 | choice | option”@Steerpike如果在测试中运行它,
testChoices
会返回什么?好,我已经完全改变了我处理这个问题的方式,但我认为这样做并在编辑中解释比开始另一个问题问本质上相同的问题要好。