摩卡控制台日志显示对象承诺

mocha console log shows object promise

开始掌握 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);
    });
  });  

此测试 returns 通过,但 console.log 输出 - [object Promise] - [object Promise] 这是为什么,期望测试很高兴他们匹配

那是因为你误用了 console.log() 语句中的 await

当你得到 recipeNamerecipeLabel 时你应该 await 因为 getText() return 是 Promise.

因为 console.log() 没有 return Promise 你不需要 await 它。

作为旁注,通过 awaiting console.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);