【问题标题】:mocha console log shows object promisemocha 控制台日志显示对象承诺
【发布时间】:2021-01-02 17:41:06
【问题描述】:

开始掌握 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] 为什么会这样,expect 测试很高兴他们匹配

【问题讨论】:

    标签: selenium mocha.js


    【解决方案1】:

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

    当你得到recipeNamerecipeLabel时你应该await,因为getText()返回一个Promise

    由于console.log() 不会返回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);
    

    【讨论】:

      猜你喜欢
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-17
      • 2019-06-03
      • 1970-01-01
      • 2019-03-23
      • 1970-01-01
      相关资源
      最近更新 更多