首页 > 解决方案 > 使用 selenium javascript webdriver 的 selenium 测试失败

问题描述

我已经安装javascript selenium webdriver并编写了这样的第一个测试

我正在编写登录测试。我输入正确的用户名和密码并尝试登录。

describe('Checkout Google.com', function () {
let driver;
before(async function () {
    // driver = await new Builder().forBrowser('chrome').build();
});
it('Search on Google', async function () {
    let driver = await new Builder().forBrowser('chrome').build();
    await driver.get('http://alpdev.s3-website-us-east-1.amazonaws.com/');
    // await driver.findElement(By.name('q')).sendKeys('selenium', Key.RETURN);
    this.timeout(5000);
    await driver.findElement(By.xpath("//input[@placeholder='Email']")).sendKeys('owais@demoshop.com');
    await driver.findElement(By.xpath("//input[@placeholder='Password']")).sendKeys('test');
    await driver.findElement(By.className('btn-submit')).click().then(()=> done());
    // assert.equal(title, 'dalenguyen - Google Search');
   });
    // close the browser after running tests
    after(() => driver && driver.quit());
 })

而我的包json是这样的

{
   "name": "selenium-01",
   "version": "1.0.0",
   "description": "",
   "main": "index.js",
   "scripts": {
     "test": "mocha --recursive index.js"
   },
   "author": "",
   "license": "ISC",
   "dependencies": {
     "mocha": "^7.2.0",
     "selenium-webdriver": "^4.0.0-alpha.7"
   }
}

现在,当我运行时ng run test,浏览器打开并通过视觉测试,这意味着登录正在发生,但在控制台上打印如下

在此处输入图像描述

这里有什么问题,它给出了一个错误。

标签: javascriptseleniumselenium-webdrivermocha.js

解决方案


因此,我无法完全重现您的案例,因为脚本中的url不再可用,但发现了一些缺陷并尝试了一些修复。

首先是你driver被宣布了两次。

其次,我认为主要问题(您收到上述错误的原因)是您使用的then&承诺在您使用&功能done时是不需要的。asyncawait

另外,我建议您使用css定位器而不是xpaths

另一件事是你可以asyncafter();闭包中使用,你可以使用箭头函数(async () => {});而不是使用function关键字。

下面是您的示例,但有一些更改,我非常肯定它会起作用(尽管如果这一切都在谷歌搜索页面上,那么该页面上没有输入,因此这些步骤将失败,您必须添加一些额外的使用可用输入字段加载登录页面的步骤):

describe('Checkout Google.com', function () {
    let driver;
    before(async () => {
        driver = await new Builder().forBrowser('chrome').build();
    });

    it('Search on Google', async () => {
        await driver.get('http://alpdev.s3-website-us-east-1.amazonaws.com/');
        await driver.findElement(By.name('q')).sendKeys('selenium', Key.RETURN);
        await driver.sleep(5000);

        // the steps below will fail as per the description above
        await driver.findElement(By.css("input[placeholder='Email']")).sendKeys('owais@demoshop.com');
        await driver.findElement(By.css("input[placeholder='Password']")).sendKeys('test');
        await driver.findElement(By.className('btn-submit')).click();
        // assert.equal(title, 'dalenguyen - Google Search');
    });

    // close the browser after running tests
    after(async () => {
        await driver.quit();
    });
});

我希望这会有所帮助,请告诉我。


推荐阅读