首页 > 解决方案 > mocha 控制台日志显示对象承诺

问题描述

开始掌握摩卡咖啡但我不明白的一件事,在下面的代码中

describe('03 Test recent recipe test', () => {
    it('Test search async', async () => {
        await driver.wait(until.elementLocated(By.name('selectit')));
        var recipeName = driver.findElement(By.name('selectit')).getText(); 
        driver.findElement(By.name('selectit')).click();
        await driver.wait(until.elementLocated(By.id('name')));
        var recipeLabel = driver.findElement(By.id('name')).getText(); 
        await console.log(recipeName + " - " + recipeLabel);
        expect(recipeName).to.contain(recipeLabel);
    });
  });  

此测试作为通过返回,但 console.log 输出 - [object Promise] - [object Promise] 为什么会这样,期望测试很高兴它们匹配

标签: seleniummocha.js

解决方案


那是因为你误用了awaitonconsole.log()声明。

await当你得到recipeNameandrecipeLabel因为getText()返回 a时,你应该这样做Promise

由于console.log()不返回 aPromise你不需要await它。

作为旁注,通过awaitingconsole.log()声明,它不会解决其中的承诺。

您的代码应如下所示:

describe('03 Test recent recipe test', () => {
    it('Test search async', async () => {
        await driver.wait(until.elementLocated(By.name('selectit')));
        var recipeName = await driver.findElement(By.name('selectit')).getText(); 
        await driver.findElement(By.name('selectit')).click();
        await driver.wait(until.elementLocated(By.id('name')));
        var recipeLabel = await driver.findElement(By.id('name')).getText(); 
        console.log(recipeName + " - " + recipeLabel);
        expect(recipeName).to.contain(recipeLabel);
    });
  }); 

要使用变量并使用它们进行打印,console.log()您可以await在其中的每一个变量中使用它们:

    var recipeName = driver.findElement(By.name('selectit')).getText(); 
    ....
    var recipeLabel = driver.findElement(By.id('name')).getText(); 
    console.log(await recipeName + " - " + await recipeLabel);

推荐阅读